Skip to content

Instantly share code, notes, and snippets.

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

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.