函数脚本:
function tohtml(tmpl,data){
var ret = tmpl.toString().match(/\/\*>([\s\S]*?)<\*\//)[1];//取得 html 代码模板
ret = ret.replace(/\$\{\{[^${{]+\}\}/g, function (variable) {
variable = variable.replace('${{', '').replace('}}', '');//取得模板中的变量名
var value = data;
variable.split('.').forEach(function (section) {
if(value && value[section]){
value = value[section]; //取得该变量对应的值
}else{ value = "${{"+variable+"}}"; }//该变量没有值
}); //console.log(variable,value);
return value;
});//替换模板中的${{变量名}}为对应的值
return ret;
}
调用例程:
html_code = tohtml(
function(){/*>
12${{text1}}34${{data.text2}}56${{data.text3}}78${{data1}}90${{data1.text4}}
<*/},
{ text1:"+",
data:{
text2:"-",
}
});
console.log("html_code" , html_code);
运行结果:
html_code
12+34-56${{data.text3}}78${{data1}}90${{data1.text4}}