<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="../js/jquery/jquery-3.1.1.js"></script>
</head>
<body>
<div id="ab">
</div>
<script type="text/html" id="tpl">
{{
for(var i in data.users){
var user=data.users[i];
}}
<p>{{r+=user.user;}}</p>
{{ } }}
</script>
<script>
var data={users:[{user:'wym'},{user:'xjm'}]};
var tpl=$('#tpl').html();
var str=templet(tpl,data);
$('#ab').html(str);
function templet(tpl, data) {
var code="";
var i;
var b=0;
var a=0;
for(i=0;i<tpl.length-1;i++){
var c=tpl[i];
var d=tpl[i+1];
if(a===0&&c==='{'&&d==='{'){
if(b===0){
code+="var r='"+tpl.substring(b,i)+"';";
}else{
code+="r+='"+tpl.substring(b,i)+"';";
}
b=i+2;
i++;
a=1;
}else if(a===1&&c==='}'&&d==='}'){
code+=tpl.substring(b,i);
b=i+2;
i++;
a=0;
}else if(a===0&&c==='\n'){
if(b===0){
code+="var r='"+tpl.substring(b,i)+"\\n';";
}else{
code+="r+='"+tpl.substring(b,i)+"\\n';";
}
b=i+1;
}
}
code+="r+='"+tpl.substring(b,i)+"';return r;";
var fn=new Function("data",code);
return fn(data);
}
</script>
</body>
</html>
写了一个最简单的 js 模板引擎,直接贴代码
最新推荐文章于 2023-10-21 12:06:02 发布