Created
June 15, 2017 08:44
-
-
Save DrAzraelTod/2dd57e1294c45b4649c8691c4edb8e50 to your computer and use it in GitHub Desktop.
shamelessly copied/extended, minimal JS-Templating engine - original: http://krasimirtsonev.com/blog/article/Javascript-template-engine-in-just-20-line
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
/** | |
* Parses complex HTML-Templates and inserts vars from a dictionary | |
* Simple Example: | |
* Template: "<p>Hello, my name is <%name%>. I\'m <%age%> years old.</p>" | |
* Options: {name: 'foobar', age: 23} | |
* | |
* More complex example: | |
* Template: "<% if(this.flowers.length > 0) { %> | |
* <ul> | |
* <% for(var i in this.flowers) { %> | |
* <li><%this.flowers[i]%></li> | |
* <% } %> | |
* </ul> | |
* <% } else {%> | |
* <p>no flowers for you</p> | |
* <% } %>" | |
* Options: {flowers: ['orchid', 'daisy']} | |
* | |
* | |
* @param html the template | |
* @param options dictionary containing replacement options | |
* @returns {*} the filled template code | |
*/ | |
var parse_template = function(html, options) { | |
$.each(template_functions,function (key,value) { | |
options[key] = value; | |
}); | |
var re = /<%([^%]+)?%>/g, reExp = /(^(\s)?(if|for|else|switch|case|break|{|}))(.*)?/gi, 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)); | |
code += 'return r.join("");'; | |
return new Function(code.replace(/[\r\t\n]/g, '')).apply(options); | |
}; | |
var template_functions = { | |
// now some functions that can be used right from templates | |
include: function (name, params, ajax_params) { | |
params = window.helpers.templates._ensure_dict(params); | |
ajax_params = window.helpers.templates._ensure_dict(ajax_params); | |
ajax_params["async"] = false; | |
var template = window.helpers.templates.fetch(name, ajax_params); | |
return window.helpers.templates.parse_template(template, params); | |
}, | |
img_url: function(img) { | |
return settings.proto + '//' + settings.host + settings.root + '/img/' + img; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment