Last active
April 1, 2019 09:05
-
-
Save thybzi/1e46eb8b23c11d55752ae4ac89a1cd13 to your computer and use it in GitHub Desktop.
The lightest JS template engine ever! (And the most 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 lightest JS template engine ever! (And the most unsafe one) | |
* Only replaces variables inside {{ }} (without any escaping) | |
* @param {string} template | |
* @param {object} data | |
* @example | |
* tpl( | |
* '<div class="{{ classname }}">{{item.title}}</div>', | |
* { classname: 'ololo', item: { ad: 'zzz', title: 'afffa!!bazinga' } } | |
* ); | |
* @returns {string} | |
* @see https://gist.github.com/thybzi/1e46eb8b23c11d55752ae4ac89a1cd13 | |
*/ | |
function tpl(template, data) { | |
return template.replace(/{{([^}]+)}}/g, function (match, expr) { | |
return eval('data.' + expr.trim()); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also
tpl2()
for escaped/unescaped variable replaceshttps://gist.github.com/thybzi/6fa7b370f1279334c0e9f3b96c06318e