Skip to content

Instantly share code, notes, and snippets.

@cuibonobo
Created May 10, 2016 21:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuibonobo/03e295658dce159cac1ea30ea6819043 to your computer and use it in GitHub Desktop.
Save cuibonobo/03e295658dce159cac1ea30ea6819043 to your computer and use it in GitHub Desktop.
A very simple template engine for Javascript.
/*
A very (*very*) simple templating function taken from
http://krasimirtsonev.com/blog/article/Javascript-template-engine-in-just-20-line
The full function includes support for if statements, for loops and other
control structures, but I stripped those out to keep it as simple and fast as
possible.
You use it like this:
var rendered = TemplateEngine(html_string, data_object);
*/
function TemplateEngine(tpl, data) {
var re = /<%([^%>]+)?%>/g,
code = 'var r=[];\n',
cursor = 0, match;
var add = function(line, js) {
js? code += 'r.push(' + line + ');\n' :
code += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
}
var match;
while(match = re.exec(tpl)) {
add(tpl.slice(cursor, match.index));
add(match[1], true);
cursor = match.index + match[0].length;
}
add(tpl.substr(cursor, tpl.length - cursor));
code += 'return r.join("");';
return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment