Skip to content

Instantly share code, notes, and snippets.

@thybzi
Last active April 1, 2019 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thybzi/1e46eb8b23c11d55752ae4ac89a1cd13 to your computer and use it in GitHub Desktop.
Save thybzi/1e46eb8b23c11d55752ae4ac89a1cd13 to your computer and use it in GitHub Desktop.
The lightest JS template engine ever! (And the most unsafe one)
/**
* 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());
});
}
@thybzi
Copy link
Author

thybzi commented Feb 28, 2017

See also tpl2() for escaped/unescaped variable replaces
https://gist.github.com/thybzi/6fa7b370f1279334c0e9f3b96c06318e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment