Skip to content

Instantly share code, notes, and snippets.

@yemster
Last active January 28, 2021 21:17
Show Gist options
  • Save yemster/b4b62e31fbb95a84b45b00b7958e6bcc to your computer and use it in GitHub Desktop.
Save yemster/b4b62e31fbb95a84b45b00b7958e6bcc to your computer and use it in GitHub Desktop.
Adequate template engine - Minimalist but entirely more than adequate Js templating engine
/*****************************************
* Usage:
* engine = Adqt.TemplateEngine
* template = 'My name is <% this.name %>'
* hash = { name: 'Yemi' }
*
* compiled = engine.compile(template) // => "var r=[]; r.push("My name is "); r.push( this.name ); return r.join("");"
* engine.render(compiled, hash) // => My name is Yemi
*
* engine.render(compiled, { name: 'Mike' }) // => My name is Mike
*****************************************/
window.Adqt = window.Adqt || {};
Adqt.TemplateEngine = (function() {
var compileTemplate = function(html) {
var re = /<%([^%>]+)?%>/g,
reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
code = 'var r=[];\n',
cursor = 0,
match;
var add = function(line, js) {
js? (code += line.match(reExp) ?
line + '\n' : 'r.push(' + line + ');\n') :
(code += line !== '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
return add;
}
while(match = re.exec(html)) {
add(html.slice(cursor, match.index))(match[1], true);
cursor = match.index + match[0].length;
}
add(html.substr(cursor, html.length - cursor));
return code += 'return r.join("");';
},
renderTemplate = function(tmpl, obj) {
return new Function(tmpl.replace(/[\r\t\n]/g, '')).apply(obj);
};
return {
compile: function(html) {
console.log('Boogie - begin template compile to cache away')
return compileTemplate(html)
},
render: function(tmpl, obj) {
console.warn('Cooking-on-gas!')
return renderTemplate(tmpl, obj)
}
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment