Skip to content

Instantly share code, notes, and snippets.

@vukicevic
Last active January 1, 2016 07:39
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 vukicevic/8112856 to your computer and use it in GitHub Desktop.
Save vukicevic/8112856 to your computer and use it in GitHub Desktop.
Simple javascript template function. Pre-prepared templates are created on the page, and then parsed/compiled. Variables are set with {{var}} and repeating sections with {{#sec}} ... {{/sec}}. Content is passed as JSON.
function TemplateEngine(templ) {
if (typeof templ != "undefined")
templ = document.getElementById(templ).innerHTML.replace(/\n|\r/g, "").replace(/>\s+</g, "><").trim();
return function compile(data, template) {
var match, tpart, i, template = template || templ;
while (match = /\{\{#([a-zA-Z]+)\}\}(.+)\{\{\/\1\}\}/g.exec(template)) {
for (tpart = '', i = 0; i < data[match[1]].length; i++)
tpart += compile(data[match[1]][i], match[2]);
template = template.split(match[0]).join(tpart);
delete data[match[1]];
}
for (match in data)
template = template.split('{{'+match+'}}').join(data[match]);
return template;
}
}
Template Example:
<script type="text/html" id="test-template">
<p>{{intro}}</p>
<ul>{{#items}}<li>{{data}}</li>{{/items}}</ul>
</script>
Usage example:
var build = TemplateEngine('test-template'),
content = { intro: "Abcdefg",
items: [{data: "item 1"},
{data: "item 2"}]
};
document.body.insertAdjacentHTML('beforeend', build(content));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment