Last active
July 14, 2016 19:30
-
-
Save carlosvega20/5f50b5606584f2168bc98d3c96a6269b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//based on https://github.com/krasimir/absurd/blob/master/lib/processors/html/helpers/TemplateEngine.js | |
//Basic | |
var TemplateEngine = function(tpl, data) { | |
var re = /<%(.+?)%>/g, match; | |
while(match = re.exec(tpl)) { | |
tpl = tpl.replace(match[0], data[match[1]]) | |
} | |
return tpl; | |
} | |
var template = 'Hello, my name is <%one%>. I\'m <%two%> years old.'; | |
console.log(TemplateEngine(template, { | |
one: "Krasimir", | |
two: 29 | |
})); | |
// Advance | |
var TemplateEngine = function(html, options) { | |
var re = /<%(.+?)%>/g, | |
reExp = /(^( )?(var|if|for|else|switch|case|break|{|}|;))(.*)?/g, | |
code = 'with(obj) { var r=[];\n', | |
cursor = 0, | |
result; | |
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 = (code + 'return r.join(""); }').replace(/[\r\t\n]/g, ' '); | |
try { result = new Function('obj', code).apply(options, [options]); } | |
catch(err) { console.error("'" + err.message + "'", " in \n\nCode:\n", code, "\n"); } | |
return result; | |
} | |
var template = | |
'My skills:' + | |
'<%if(this.showSkills) {%>' + | |
'<%for(var index in this.skills) {%>' + | |
'<a href="#"><%this.skills[index]%></a>' + | |
'<%}%>' + | |
'<%} else {%>' + | |
'<p>none</p>' + | |
'<%}%>'; | |
console.log(TemplateEngine(template, { | |
skills: ["js", "html", "css"], | |
showSkills: true | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment