var result = tpl(
'aaa<b>{one}</b>fd<ul>'+
'<% for (var i = 0;i < four.length;i++) { %>'+
'<li>{four[i]}</li>'+
'<% } %></ul>',{
one:'223ew',
two:'213esde',
three: {
aaa: 1234,
bbb: true,
},
four:[1,234,5,7,33]
}
);
document.write(result);
function tpl ( html , data ) {
var re = /<%([^%>]+)%>/g,
code = 'var r=[];\n',
cursor = 0;
var addCode = function(line , js) {
js ? code += 'r.push(' + line + ');\n' :
code += 'r.push("' + line.replace(/"/g , '\\"') + '");\n';
}
while( match = re.exec(html) ) {
addCode( html.slice( cursor , match.index ) );
addCode( match[1] , true );
cursor = match.index + match[0].length;
}
addCode( html.substr(cursor, html.length - cursor) );
code += 'return r.join("");';
console.log( code );
return new Function( code.replace(/[\r\t\n]/g,'') ).apply(data);
};
console