Skip to content

Instantly share code, notes, and snippets.

@thybzi thybzi/tpl2.js
Last active Apr 1, 2019

Embed
What would you like to do?
The second lightest JS template engine! (And still so unsafe one)
/**
* The second lightest JS template engine! (And still so unsafe one)
* Only replaces variables inside {{ }} (HTML-escaped) and {{{ }}} (unescaped)
* Second lightest after the original https://gist.github.com/thybzi/1e46eb8b23c11d55752ae4ac89a1cd13
* @param {string} template
* @param {object} data
* @returns {string}
* @example
* tpl2(
* '<div class="{{ classname }}">{{{ item.content }}}</div>',
* { classname: 'ololo', item: { useless: 'one', content: '<em>afffa!!</em> bazinga' } }
* );
* @see https://gist.github.com/thybzi/6fa7b370f1279334c0e9f3b96c06318e
*/
function tpl2(template, data) {
return template
// Replace unescaped vars
.replace(/{{{([^}]+)}}}/g, function (_m, expr) {
return _getValue(expr);
})
// Replace escaped vars
.replace(/{{([^}]+)}}/g, function (_m, expr) {
return _getValue(expr, true);
});
/**
* Get value from data
* @param {string} expr
* @param {boolean} [escape]
* @returns {*}
* @private
*/
function _getValue(expr, escape) {
var value = eval('data.' + expr.trim()).toString();
return escape ? _escapeHtml(value) : value;
}
/**
* Escape string for use inside HTML attribute value
* @param {string} input
* @returns {string}
* @private
* @see http://stackoverflow.com/a/6234804/3027390
*/
function _escapeHtml(input) {
return input
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
}
@thybzi

This comment has been minimized.

Copy link
Owner Author

commented Apr 1, 2019

Original 3-line tpl() (but without escaping):
https://gist.github.com/thybzi/1e46eb8b23c11d55752ae4ac89a1cd13

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.