模板引擎是第三方模块。
让开发者以更加有好的方式拼接字符串,使项目代码更加清晰,更加易于维护。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