简单的 js 模版引擎
var tplEngine = function(tpl, data) {
var reg = /<%([^%>]+)?%>/g,
regOut = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
code = 'var r=[];
',
cursor = 0;
var add = function(line, js) {
js? (code += line.match(regOut) ? line + '
' : 'r.push(' + line + ');
') :
(code += line != '' ? 'r.push("' + line.replace(/"/g, '\"') + '");
' : '');
return add;
}
while(match = reg.exec(tpl)) {
add(tpl.slice(cursor, match.index))(match[1], true);
cursor = match.index + match[0].length;
}
add(tpl.substr(cursor, tpl.length - cursor));
code += 'return r.join("");';
return new Function(code.replace(/[
]/g, '')).apply(data);
};
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(tplEngine(template, {
skills: ["js", "html", "css"],
showSkills: true
}));