在浏览器中使用art-template模板引擎
模板引擎分很多种,art-template是其中一种模板引擎。
安装教程:
1.新建一个空白文件夹,cd进入
2.首先执行初始化操作:npm init
3.然后安装art-template模板引擎: npm i art-template --save
在node_modules文集夹中找到template-web.js文件。

新建一个index.js文件。
使用模板引擎.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="node_modules/art-template/lib/template-web.js"></script>
<script type="text/template" id="tpl">
{{ name }}
</script>
<script>
const app = template('tpl', {
name: '小明'
})
console.log(app)
</script>
</body>
</html>
使用模板引擎的注意事项:

小结:模板引擎不关心内容,只关心模板标记语法,语法类似vue的双大括{{}}八字胡号的学习。
demo:


为什么说模板引擎不关心内容呢?
看下下面这个demo就知道了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="node_modules/art-template/lib/template-web.js"></script>
<script type="text/template" id="tpl">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
我叫{{ name }}
来自{{ province }}
今年{{ age }}
爱好{{ each hobbies }} {{ $value }} {{ /each }}
</body>
</html>
</script>
<script>
const app = template('tpl', {
name: '小明',
province: '广东省江门市',
age: 21,
hobbies: [
'羽毛球',
'追剧',
'听音乐'
]
})
console.log(app)
</script>
</body>
</html>
我们使用再使用一层<!DOCTYPE html>包裹着代码。

照样给你当字符串解析出来,所以说模板引擎他是不关注内容的,它只认识{{}}这个标记语法。
模板引擎最早诞生于服务器端,后来发展到了前端。
在node环境中使用art-template模板引擎
在node中使用art-template模板引擎需要使用require方法。
新建一个index.js文件。
demo1,基本用法如下:
const template = require('art-template')
const result = template.render('hello {{ name }}', {
name: 'world'
})
console.log(result)

使用模板字符串,demo2:
const template = require('art-template')
const TPL = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
我叫{{ name }}
来自{{ province }}
今年{{ age }}
爱好{{ each hobbies }} {{ $value }} {{ /each }}
</body>
</html>
`
const result = template.render(TPL, {
name: '小明',
province: '广东省江门市',
age: 21,
hobbies: [
'羽毛球',
'追剧',
'听音乐'
]
})
console.log(result)
上面这种写法太过冗余,不够简洁,我们可以做抽离,将TPL抽离成一个TPL.html文件。

在index.js文件中读取。
const template = require('art-template')
const fs = require('fs')
fs.readFile('./TPL.html', (err, data) => {
if (err) {
return console.log('读取文件失败')
}
/*默认读取到的data是二进制数据,而模板引擎的render()方法需要接收的字符串
所以我们在这里需要将data二进制数据转换为字符串,才可以给模板引擎使用
采用toString()方法
*/
const result = template.render(data.toString(), {
name: '小明',
province: '广东省江门市',
age: 21,
hobbies: [
'羽毛球',
'追剧',
'听音乐'
]
})
console.log(result)
})
效果:

网友评论