Last active
April 1, 2019 09:05
-
-
Save thybzi/6fa7b370f1279334c0e9f3b96c06318e to your computer and use it in GitHub Desktop.
The second lightest JS template engine! (And still so unsafe one)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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, '&') | |
.replace(/</g, '<') | |
.replace(/>/g, '>') | |
.replace(/"/g, '"') | |
.replace(/'/g, '''); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original 3-line
tpl()
(but without escaping):https://gist.github.com/thybzi/1e46eb8b23c11d55752ae4ac89a1cd13