Last active
January 1, 2016 07:39
-
-
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.
This file contains 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
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