1doT.js github地址:
http://olado.github.io/doT/
实例1:简单
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title></title>
- <script type="text/javascript" src="../../doT.js"></script>
- <script type="text/javascript" src="http://hbjltv.com/static/js/jquery-1.11.1.js"></script>
- </head>
- <body>
- <div id="interpolationtmpl">
- <div>Hi {{=it.name}}!</div>
- <div>{{=it.age || ''}}</div>
- </div>
- <hr/>
- <div id="interpolation"></div>
- <script type="text/javascript">
- var dataInter = {"name": "Jake", "age": 31};
- var interText = doT.template($("#interpolationtmpl").html());
- $("#interpolation").html(interText(dataInter));
- </script>
- </body>
- </html>
运行结果:
实例二:条件判断
- <body>
- <div id="conditionstmpl">
- {{? !it.name }}
- <div> 你还没有名字</div>
- {{?? }}
- <div>Oh, I love your name, {{=it.name}}!</div>
- {{?}}
- </div>
- <hr/>
- <div id="condition"></div>
- <script type="text/javascript">
- var dataEncode = {"name": "黄威", "age": 31};
- var interText = doT.template($("#conditionstmpl").html());
- $("#condition").html(interText(dataEncode));
- </script>
- </body>
运行结果:
实例三:循环+条件判断
- <body>
- <div id="evaluationtmpl">
- {{ for(var prop in it) { }}
- {{? typeof it[prop]=='object' }}
- <div style="font-weight: bold;" >KEY:{{= prop }}---VALUE:</div>
- {{ for(var prop2 in it[prop]) { }}
- <div style="margin-left: 20px;" >key:{{= prop2 }}---value:{{= it[prop][prop2] }}</div>
- {{ } }}
- {{?? }}
- <div>KEY:{{= prop }}---VALUE:{{= it[prop] }}</div>
- {{?}}
- {{ } }}
- </div>
- <hr/>
- <div id="evaluation"></div>
- <script type="text/javascript">
- var dataEval = {
- "name": "Jake",
- "age": 31,
- "interests": ["basketball", "hockey", "photography"],
- "contact": {"email": "jake@xyz.com", "phone": "999999999"}
- };
- var evalText = doT.template($("#evaluationtmpl").html());
- $("#evaluation").html(evalText(dataEval));
- </script>
- </body>
运行结果:
源码下载地址:
http://pan.baidu.com/s/1c0HFyb2
说明:1,{{? typeof it[prop]=='object' }} 表示条件判断,结束标签是{{?}}2, {{?? }}是条件判断的else3,{{ 和{{? 中均可以使用原生的js语法,如for,typeof 等4,模板并不是一定要放在script标签中,也可以放在隐藏的div标签中
时间: 2024-10-28 08:26:05