doT 模板一般是放在script脚本里面的,例如:
- <!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>
- <script id="conditionstmpl">
- {{ if(!it.name){ }}
- <div> 你还没有名字</div>
- {{ } else { }}
- <div>Oh, I love your name, {{=it.name}}!</div>
- {{ } }}
- </script>
- <hr/>
- <div id="condition"></div>
- <script type="text/javascript">
- var dataEncode = {"name": "", "age": 31};
- var interText = doT.template($("#conditionstmpl").text());
- $("#condition").html(interText(dataEncode));
- </script>
- </body>
- </html>
但是我不太喜欢放在script标签中,我喜欢把模板放在div中,如下:
- <body>
- <div id="conditionstmpl">
- {{? it.name }}
- <div>Oh, I love your name, {{=it.name}}!</div>
- {{?? !it.age == 0}}
- <div>Your age is {{=it.age}}</div>
- {{??}}
- You don't have age and still don't have a name?
- {{?}}
- </div>
- <hr/>
- <div id="condition"></div>
- <script type="text/javascript">
- var dataEncode ={"name":"","age":0};
- var interText = doT.template($("#conditionstmpl").html());
- $("#condition").html(interText(dataEncode));
- </script>
- </body>
但是下面的代码就出现了问题:
报错信息如下:
这是为什么呢?因为js在获取div的内容时,自动把div中的内容进行了转义:
< | < ; |
> | > ; |
即把小于号变成了< ; ,这不是我预期的.因为html把<转化成了< ;,所以doT 报错了.
解决方法:使用如下方法还原
- /***
- * Html解码获取Html实体<br>
- * '<'--> '<'
- * @param value
- * @returns {*|jQuery}
- */
- function htmlDecode(value){
- return $('<div/>').html(value).text();
- }
处理模板的js:
- var evalText = doT.template(htmlDecode($invoiceListDot.html()));
- $invoiceListDiv.html(evalText(invoiceInfoDtos));
参考:http://blog.****.net/hw1287789687/article/details/46671437