模板引擎的好处:
1.减少了字符串的拼接操作
2.使代码结构更清晰
3.使代码更易于阅读与维护
art-template 是一个简约、超快的模板引擎。可以根据指定的模板结构和数据,自动生成一个完整的HTML页面。
在浏览器中访问 http://aui.github.io/art-template/zh-cn/docs/installation.html 页面,找到下载链接后,鼠标右键,选择“链接另存为”,将 art-template 下载到本地,然后,通过 <script> 标签加载到网页上进行使用。
art-template的使用步骤
1.导入 art-template
2.定义数据
3.定义模板(模板的 HTML 结构,必须定义到 script 中)
4.调用 template 函数
5.渲染HTML结构
art-template 提供了 {{ }} 这种语法格式,在 {{ }} 内可以进行变量输出,或循环数组等操作。
<h1>{{name}} ------ {{age}}</h1>
如果要输出的 value 值中,包含了 HTML 标签结构,则需要使用原文输出语法,才能保证 HTML 标签被正常渲染。
<body>
<div id="container"></div>
<script type="text/html" id="tpl-user">
{{@ test}}
</script>
<script>
var data = { name: 'zs', age: 20, test: '<h3>测试原文输出</h3>', flag: 1, hobby: ['吃饭', '睡觉', '写代码'], regTime: new Date() }
var htmlStr = template('tpl-user', data)
console.log(htmlStr)
$('#container').html(htmlStr)
</script>
</body>
如果要实现条件输出,则可以在 {{ }} 中使用 if … else if … /if 的方式,进行按需输出。
{{if value}} 按需输出的内容 {{/if}}
{{if v1}} 按需输出的内容 {{else if v2}} 按需输出的内容 {{/if}}
<body>
<div id="container"></div>
<!-- 3. 定义模板 -->
<!-- 3.1 模板的 HTML 结构,必须定义到 script 中 -->
<script type="text/html" id="tpl-user">
<div>
{{if flag === 0}}
flag的值是0
{{else if flag === 1}}
flag的值是1
{{/if}}
</div>
</script>
<script>
var data = { name: 'zs', age: 20, test: '<h3>测试原文输出</h3>', flag: 1, hobby: ['吃饭', '睡觉', '写代码'], regTime: new Date() }
var htmlStr = template('tpl-user', data)
console.log(htmlStr)
$('#container').html(htmlStr)
</script>
</body>
如果要实现循环输出,则可以在 {{ }} 内,通过 each 语法循环数组,当前循环的索引使用 $index 进行访问,当前的循环项使用 $value 进行访问。
{{each arr}}
{{$index}} {{$value}}
{{/each}}
<body>
<div id="container"></div>
<!-- 定义模板 -->
<!-- 1 模板的 HTML 结构,必须定义到 script 中 -->
<script type="text/html" id="tpl-user">
<h1>{{name}} ------ {{age}}</h1>
{{@ test}}
<div>
{{if flag === 0}}
flag的值是0
{{else if flag === 1}}
flag的值是1
{{/if}}
</div>
<ul>
{{each hobby}}
<li>索引是:{{$index}},循环项是:{{$value}}</li>
{{/each}}
</ul>
</script>
<script>
// 2. 定义需要渲染的数据
var data = { name: 'zs', age: 20, test: '<h3>测试原文输出</h3>', flag: 1, hobby: ['吃饭', '睡觉', '写代码'], regTime: new Date() }
// 4. 调用 template 函数
var htmlStr = template('tpl-user', data)
console.log(htmlStr)
// 5. 渲染HTML结构
$('#container').html(htmlStr)
</script>
</body>