ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### 3、实例 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <script src="./lib/template-web.js"></script> </head> <body> <div id="content"></div> <script id="test" type="text/html"> <div> <!-- 输出表达式 --> <p>{{name}}</p> <!-- 不转义输出 --> <p>{{#value}}</p> <!-- 条件表达式 --> {{if bool}} <p>{{bool}}</p> {{/if}} {{if num < 1 }} <p>'num < 1'</p> {{else}} <p>error!</p> {{/if}} <!-- 遍历表达式 数组 --> <p>遍历表达式 数组</p> {{each list as value index}} <li>{{index}}: {{value}}</li> {{/each}} <!-- $简写 $ 特指当前函数中的变量 --> <p>$简写</p> {{each list}} <li>{{$index}}: {{$value}}</li> {{/each}} <!-- 遍历表达式 对象 --> <p>遍历表达式 对象</p> {{each objList as value index}} <li>{{index}}: {{value}}</li> {{/each}} <!-- $简写 --> <p>$简写</p> {{each objList}} <li>{{$index}}: {{$value}}</li> {{/each}} <!-- 模板包含子模板,表达式 --> {{include 'news_list'}} <!-- 辅助方法 --> </div> </script> <script id="news_list" type="text/html"> <p>模板包含子模板,表达式</p> <ul> {{each list as value i}} <li>索引 {{i + 1}} :{{value + 1}}</li> {{/each}} </ul> </script> <script> const data = { name: 'zhangsan', value: '<h1>lisi</h1>', num: 0, bool: true, list: [1, 2, 3, 4, 5], objList: { name: 'zhangsan', age: '18', addr: '广东' } } let temp = template('test', data) document.getElementById('content').innerHTML = temp </script> </body> </html> ``` ![image-20200126152808449.png](https://yanxuan.nosdn.127.net/661309f275c70d0d32b5319d697cf5cf.png) ```html <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>no escape-demo</title> <script src="../dist/template.js"></script> </head> <body> <h1>不转义HTML</h1> <div id="content"></div> <script id="test" type="text/html"> <p>不转义:{{#value}}</p> <p>默认转义: {{value}}</p> </script> <script> var data = { value: '<span style="color:#F00">hello world!</span>' }; var html = template('test', data); document.getElementById('content').innerHTML = html; </script> </body> </html> ``` ![image-20200126152827260.png](https://yanxuan.nosdn.127.net/3c6e9a272415409bb76dfa208eea9f06.png) ```html <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>include-demo</title> <script src="../dist/template.js"></script> </head> <body> <div id="content"></div> <script id="test" type="text/html"> <h1>{{title}}</h1> {{include 'list'}} </script> <script id="list" type="text/html"> <ul> {{each list as value i}} <li>索引 {{i + 1}} :{{value}}</li> {{/each}} </ul> </script> <script> var data = { title: '嵌入子模板', list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他'] }; var html = template('test', data); document.getElementById('content').innerHTML = html; </script> </body> </html> ``` ![image-20200126152842459.png](https://yanxuan.nosdn.127.net/5979584f9b237e913279b47fb7e2a911.png) ```html ``` ![image-20200126152920878.png](https://yanxuan.nosdn.127.net/1b3ef79d9f83050e89c7f5bcda21900a.png)