为了不用angularJS等较为重量级的,和繁琐的配置,所以就用了laytpl,可以配合JQ使用
laytpl.js源码如下:
/**
@Name:laytpl-v1.1 精妙的js模板引擎
@Author:贤心 - 2014-08-16
@Site:http://sentsin.com/layui/laytpl
@License:MIT license*/;!function(){"use strict";var f,b={open:"{{",close:"}}"},c={exp:function(a){return new RegExp(a,"g")},query:function(a,c,e){var f=["#([\\s\\S])+?","([^{#}])*?"][a||0];return d((c||"")+b.open+f+b.close+(e||""))},escape:function(a){return String(a||"").replace(/&(?!#?[a-zA-Z0-9]+;)/g,"&").replace(//g,">").replace(/‘/g,"'").replace(/"/g,""")},error:function(a,b){var c="Laytpl Error:";return"object"==typeof console&&console.error(c+a+"\n"+(b||"")),c+a}},d=c.exp,e=function(a){this.tpl=a};e.pt=e.prototype,e.pt.parse=function(a,e){var f=this,g=a,h=d("^"+b.open+"#",""),i=d(b.close+"$","");a=a.replace(/[\r\t\n]/g," ").replace(d(b.open+"#"),b.open+"# ").replace(d(b.close+"}"),"} "+b.close).replace(/\\/g,"\\\\").replace(/(?="|‘)/g,"\\").replace(c.query(),function(a){return a=a.replace(h,"").replace(i,""),‘";‘+a.replace(/\\/g,"")+‘; view+="‘}).replace(c.query(1),function(a){var c=‘"+(‘;return a.replace(/\s/g,"")===b.open+b.close?"":(a=a.replace(d(b.open+"|"+b.close),""),/^=/.test(a)&&(a=a.replace(/^=/,""),c=‘"+_escape_(‘),c+a.replace(/\\/g,"")+‘)+"‘)}),a=‘"use strict";var view = "‘+a+‘";return view;‘;try{return f.cache=a=new Function("d, _escape_",a),a(e,c.escape)}catch(j){return delete f.cache,c.error(j,g)}},e.pt.render=function(a,b){var e,d=this;return a?(e=d.cache?d.cache(a,c.escape):d.parse(d.tpl,a),b?(b(e),void 0):e):c.error("no data")},f=function(a){return"string"!=typeof a?c.error("Template not found"):new e(a)},f.config=function(a){a=a||{};for(var c in a)b[c]=a[c]},f.v="1.1","function"==typeof define?define(function(){return f}):"undefined"!=typeof exports?module.exports=f:window.laytpl=f}();
1.引用该js
2.建立的模板
3.用laytpl.js吧得到的数据加入到模板
4.把模板渲染到你要的html的demo
1
2
3
4
5
6
7
8
9 //假设你得到了这么一段数据
10 vardata={11 title:‘前端圈‘,12 intro:‘一群码js的骚年,幻想改变世界,却被世界改变。‘,13 list: [{ name:‘贤心‘, city:‘杭州‘}, { name:‘谢亮‘, city:‘北京‘}, { name:‘浅浅‘, city:‘杭州‘}, { name:‘Dem‘, city:‘北京‘}]14 };15
16 window.οnlοad= function() {17 //建立视图。用于呈现渲染结果。
18 vargettpl=document.getElementById(‘testTpl‘).innerHTML;19 laytpl(gettpl).render(data,function(html) {20 //得到的模板渲染到html
21 document.getElementById(‘testDiv‘).innerHTML=html;22 });23 }24
25
26
27
28
29
{{d.intro}}
30
31 {{#for(vari= 0; i
33 姓名:{{ d.list[i].name }}
34 城市:{{ d.list[i].city }}
35
36 {{# } }}37
38
39