Simple_Js_Templating

by amindunited

HTML

<div id="template">The template should be changed to read: {{foo}}</div>
<div id="result">maaa</div>

JavaScript

(function(){
    var cache = {};  
    this.applyTemplate = function applyTemplate(template_html, template_data) {
        var func = new Function("temp_obj", "var p=[], print=function(){p.push.apply(p,arguments);};" +
                                "with(temp_obj){p.push('"+
                                
                                template_html
                                .replace(/[\r\t\n]/g, " ")
                                .split("{{").join("\t")
                                .replace(/((^|}})[^\t]*)'/g, "$1\r")
                                .replace(/\t(.*?)}}/g, "',$1, '")
                                .split("\t").join("');")
                                .split("}}").join("p.push('")
                                .split("\r").join("\\'")
                                +"');}return p.join('');");
        return template_data ? func( template_data) : func;
    }        
 
})();
    
$(document).ready(function(){
    var template_data = {foo: " This is a newer sentance"}
    var template_html = document.getElementById('template').innerHTML;
    document.getElementById('result').innerHTML = applyTemplate(template_html, template_data);
});