1.模板引擎
模板引擎是第三方模塊。
讓開(kāi)發(fā)者以更加友好的方式拼接字符串,使項(xiàng)目代碼更加清晰、更加易于維護(hù)。
// 未使用模板引擎的寫(xiě)法
var ary = [{ name: '張三', age: 20 }];
var str = '<ul>';
for (var i = 0; i < ary.length; i++) {
str += '<li>\
<span>'+ ary[i].name +'</span>\
<span>'+ ary[i].age +'</span>\
</li>';
}
str += '</ul>';
<!-- 使用模板引擎的寫(xiě)法 -->
<ul>
{{each ary}}
<li>{{$value.name}}</li>
<li>{{$value.age}}</li>
{{/each}}
</ul>
2.art-template模板引擎使用
- 在命令行工具中使用 npm install art-template 命令進(jìn)行下載
- 使用const template = require('art-template')引入模板引擎
- 告訴模板引擎要拼接的數(shù)據(jù)和模板在哪 const html = template(‘模板路徑’, 數(shù)據(jù));
- 使用模板語(yǔ)法告訴模板引擎,模板與數(shù)據(jù)應(yīng)該如何進(jìn)行拼接
3. art-template代碼示例
// 導(dǎo)入模板引擎模塊
const template = require('art-template');
// 將特定模板與特定數(shù)據(jù)進(jìn)行拼接
const html = template('./views/index.art',{
data: {
name: '張三',
age: 20
}
});
<div>
<span>{{data.name}}</span>
<span>{{data.age}}</span>
</div>
4.模板引擎語(yǔ)法
4.1 模板語(yǔ)法
- art-template同時(shí)支持兩種模板語(yǔ)法:標(biāo)準(zhǔn)語(yǔ)法和原始語(yǔ)法。
- 標(biāo)準(zhǔn)語(yǔ)法可以讓模板更容易讀寫(xiě),原始語(yǔ)法具有強(qiáng)大的邏輯處理能力
標(biāo)準(zhǔn)語(yǔ)法: {{ 數(shù)據(jù) }}
原始語(yǔ)法:<%=數(shù)據(jù) %>
4.2 輸出
將某項(xiàng)數(shù)據(jù)輸出在模板中,標(biāo)準(zhǔn)語(yǔ)法和原始語(yǔ)法如下:
- 標(biāo)準(zhǔn)語(yǔ)法:{{ 數(shù)據(jù) }}
- 原始語(yǔ)法:<%=數(shù)據(jù) %>
<!-- 標(biāo)準(zhǔn)語(yǔ)法 -->
<h2>{{value}}</h2>
<h2>{{a ? b : c}}</h2>
<h2>{{a + b}}</h2>
<!-- 原始語(yǔ)法 -->
<h2><%= value %></h2>
<h2><%= a ? b : c %></h2>
<h2><%= a + b %></h2>
4.3 原文輸出
如果數(shù)據(jù)中攜帶HTML標(biāo)簽,默認(rèn)模板引擎不會(huì)解析標(biāo)簽,會(huì)將其轉(zhuǎn)義后輸出。
- 標(biāo)準(zhǔn)語(yǔ)法:{{@ 數(shù)據(jù) }}
- 原始語(yǔ)法:<%-數(shù)據(jù) %>
<h2>{{@ value }}</h2>
<!-- 原始語(yǔ)法 -->
<h2><%- value %></h2>
4.4 條件判斷
<!-- 標(biāo)準(zhǔn)語(yǔ)法 -->
{{if 條件}} ... {{/if}}
{{if v1}} ... {{else if v2}} ... {{/if}}
<!-- 原始語(yǔ)法 -->
<% if (value) { %> ... <% } %>
<% if (v1) { %> ... <% } else if (v2) { %> ... <% } %>
4.5 循環(huán)
- 標(biāo)準(zhǔn)語(yǔ)法:{{each 數(shù)據(jù)}} {{/each}}
- 原始語(yǔ)法:<% for() { %> <% } %>
<!-- 標(biāo)準(zhǔn)語(yǔ)法 -->
{{each target}}
{{$index}} {{$value}}
{{/each}}
<!-- 原始語(yǔ)法 -->
<% for(var i = 0; i < target.length; i++){ %>
<%= i %> <%= target[i] %>
<% } %>
4.6 子模版
使用子模板可以將網(wǎng)站公共區(qū)塊(頭部、底部)抽離到單獨(dú)的文件中。
- 標(biāo)準(zhǔn)語(yǔ)法:{{include '模板'}}
- 原始語(yǔ)法:<%include('模板') %>
<!-- 標(biāo)準(zhǔn)語(yǔ)法 -->
{{include './header.art'}}
<!-- 原始語(yǔ)法 -->
<% include('./header.art') %>
4.7 模板繼承
使用模板繼承可以將網(wǎng)站HTML骨架抽離到單獨(dú)的文件中,其他頁(yè)面模板可以繼承骨架文件。
模板示例
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML骨架模板</title>
{{block 'head'}}{{/block}}
</head>
<body>
{{block 'content'}}{{/block}}
</body>
</html>
繼承示例
<!--index.art 首頁(yè)模板-->
{{extend './layout.art'}}
{{block 'head'}} <link rel="stylesheet" href="custom.css"> {{/block}}
{{block 'content'}} <p>This is just an awesome page.</p> {{/block}}
4.8模板配置
- 向模板中導(dǎo)入變量 template.defaults.imports.變量名 = 變量值;
- 設(shè)置模板根目錄 template.defaults.root = 模板目錄
- 設(shè)置模板默認(rèn)后綴 template.defaults.extname = '.art'