art-template
High performance JavaScript templating engine https://aui.github.io/art-template/
Purpose: The server also has the ability to render templates. The
template engine does not care about the content, but only about the markup {{}}. The earliest template caused by It was born in the server field and later developed to the front end.
Steps:
1. Install npm install art-template
2. Load art-template in the document module to be used, just use the require method to load it
require('art-template')
3. Check the documentation and use the API of the template engine
//art-template
// art-template 不仅可以在浏览器使用,也可以在 node 中使用
var template = require('art-template')
var fs = require('fs')
// 这里不是浏览器
// template('script 标签 id', {对象})
// var tplStr = `
// <!DOCTYPE html>
// <html lang="en">
// <head>
// <meta charset="UTF-8">
// <title>Document</title>
// </head>
// <body>
// <p>大家好,我叫:{{ name }}</p>
// <p>我今年 {{ age }} 岁了</p>
// <h1>我来自 {{ province }}</h1>
// <p>我喜欢:{{each hobbies}} {{ $value }} {{/each}}</p>
// </body>
// </html>
// `
//新建一个tp.html,使用模版引擎
fs.readFile('./tp.html', function (err, data) {
if (err) {
return console.log('读取文件失败了')
}
// 默认读取到的 data 是二进制数据
// 而模板引擎的 render 方法需要接收的是字符串
// 所以我们在这里需要把 data 二进制数据转为 字符串 才可以给模板引擎使用
var ret = template.render(data.toString(), {
name: 'Jack',
age: 22,
province: '武汉市',
hobbies: [
'写代码',
'唱歌',
'打游戏'
],
title: '个人信息'
})
console.log(ret)
})
//Core method
// Render template
template based on template name(filename, data);
// Compile the template source code into the function
template.compile(source, options);
// Compile the template source code into a function and immediately execute
template.render(source, data, options);