简单的模板引擎,纯JS

不知道从何时起就很讨厌拼接字符串的方式改变doucument的内容

如:

context += '<li><table width="100%" border="0" cellspacing="0" cellpadding="0">'
     +'<tr><td colspan="2"><h4>'+p.parkName+'</h4><td></tr>'
        +'<tr><td><p><img src="images/outdoor.png" width="27px" height="27px"> '+p.parkTypeName+'</p></td>'
	+'</table></li>';
document.getElementById("scroller").innerHTML=context;

 那么多的单引号与双引号,超容易弄错,把自己埋了。

然后就觉得angular的模板引擎很酷炫呀,不能用js框架,肿么办?写了个简单的

如:

<script type="text" id="template">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="dingdan" >
  <tr>
	<td rowspan="4" align="center" valign="top" style="width:50px;"><img src="images/chepai.png"></td>
	<td style="width:40%;">{{carNumber}}</td>
	<td> </td>
  </tr>
</table>
</script>

 这个是写在script标签里面的,

然后用replace的正则把{{}}的内容替换

document.getElementById(id).innerHTML.replace(/{{([^}}]+)?}}/g,function(s0,s1){return order[s1]})

简单的模板引擎就完成了

暂时不知道怎么把模板放到另一个文件中。

posted @ 2015-08-18 15:23  阿克西斯教成员污米饭  阅读(229)  评论(0)    收藏  举报