在 Node.js 中使用 art-template 模板引擎

安裝

透過 npm 安裝

1
npm install art-template --save

載入模組

1
var template = require('art-template')

HTML 模板文件

template.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!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>
</head>
<body>
<p>大家好, 我叫: {{ name }}</p>
<p>我今年 {{ age }} 歲</p>
<h1>我來自 {{ province }}</h1>
<p>我喜歡:
{{ each hobbies }}
{{ $value }}
{{ /each }}
</p>
<p>
{{ if (boo)}}
{{ test[0] }}
{{ else }}
{{ test[1] }}
{{ /if }}
</p>
</body>
</html>

使用

基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fs.readFile('./template.html', function (err, data) {
if (err) {
return console.log('data readed error')
}
// 預設讀取到的 data 是二進制數據
// 而模板引擎的 render 方法需要接收字串
// 所以在這裡需要把 data 二進制數據轉換為字串, 才可以給模板引擎使用
var ret = template.render(data.toString(), {
name: 'Dylan',
age: 18,
province: '台灣',
hobbies: ['彈吉他', '寫程式', '玩滑板', '繪畫']
boo: true,
test: ['if(boo)', 'if(!boo)']
})
})

console.log(ret) 輸出字串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!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>
</head>
<body>
<p>大家好, 我叫: Dylan</p>
<p>我今年 18 歲</p>
<h1>我來自 台灣</h1>
<p>我喜歡:
彈吉他
寫程式
玩滑板
繪畫
</p>
<p>
if(boo)
</p>
</body>
</html>

資源