Created
May 10, 2016 21:40
-
-
Save cuibonobo/03e295658dce159cac1ea30ea6819043 to your computer and use it in GitHub Desktop.
A very simple template engine for Javascript.
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
/* | |
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