Skip to content

Instantly share code, notes, and snippets.

@thybzi
Last active April 1, 2019 09:05
Show Gist options
  • Save thybzi/6fa7b370f1279334c0e9f3b96c06318e to your computer and use it in GitHub Desktop.
Save thybzi/6fa7b370f1279334c0e9f3b96c06318e to your computer and use it in GitHub Desktop.
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
Copy link
Author

thybzi 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