模板引擎是第三方模塊。
讓開發者以更加有好的方式拼接字符串,使項目代碼更加清晰,更加易於維護。html
// 導入模板引擎模塊
const template = require('art-template');
// 將特定模板與特定數據進行拼接
const html = template('./views/index.art',{
data: {
name: '張三',
age: 20
}
});
<div>
<span>{{data.name}}</span>
<span>{{data.age}}</span>
</div>
2. 模板引擎語法
標準語法:{{數據}}
原始語法: <% = 數據 %>ide
將某項數據輸出在模板中,標準語法與原始語法以下:工具
<!-- 標準語法 -->
<h2>{{value}}</h2>
<h2>{{a ? b : c}}</h2>
<h2>{{a + b}}</h2>
<!-- 原始語法 -->
<h2><%= value %></h2>
<h2><%= a ? b : c %></h2>
<h2><%= a + b %></h2>
若是數據中攜帶HTML標籤,默認模板引擎不會解析標籤,會將其轉義爲輸出。網站
<!-- 標準語法 -->
<h2>{{@ value }}</h2>
<!-- 原始語法 -->
<h2><%- value %></h2>
標準語法:ui
<!-- 標準語法 -->
{{if 條件}} ... {{/if}}
{{if v1}} ... {{else if v2}} ... {{/if}}
原始語法:spa
<!-- 原始語法 -->
<% if (value) { %> ... <% } %>
<% if (v1) { %> ... <% } else if (v2) { %> ... <% } %>
<!-- 標準語法 -->
{{each target}}
{{$index}} {{$value}}
{{/each}}
<!-- 原始語法 -->
<% for(var i = 0; i < target.length; i++){ %>
<%= i %> <%= target[i] %>
<% } %>
使用子模版能夠將網站公共區塊(頭部、底部)抽離到單獨的文件中。htm
{{ include './common/header.art'}}
<% include ('./common/header.art')%>
<div>{{ msg }}</div>
<% include ('./common/footer.art')%>
{{include './common/footer.art'}}
使用模板繼承能夠將網站HTML骨架抽離到單獨的文件中,其餘頁面能夠繼承骨架文件。blog