模板引擎
模板引擎是第三方模块
让开发者以更加友好的方式拼接字符串,使项目代码更加清晰、更加易于维护。
在浏览器中使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>art-template</title>
<!-- 引用 js 文件 -->
<script src="./js/template-web.js"></script>
</head>
<body>
<div id="box"></div>
<!-- 定义模板 -->
<script id="tpl" type="text/html">
{{tit}}
<ul>
{{each list}}
<li>
{{$index}} {{$value}}
</li>
{{/each}}
</ul>
</script>
<!-- 结合数据编译 -->
<script>
const html = template('tpl', {
list: ['kobe', 'james', 'curry', 'jordan'],
tit: '数据组'
})
box.innerHTML = html
</script>
</body>
</html>
node 中使用
- 通过命令 npm install art-template --save 进行安装
- 使用 const template = require( ‘art-template’ ) 引入模板引擎
- 使用 const html = template( ‘模板路径’, 数据 ) 进行编译
npm install art-template --save
const template = require('art-template')
const path = require('path')
const views = path.join(__dirname, 'test.art')
const tpl = template(views, {
name: 'Tom',
list: ['kobe', 'james', 'curry', 'jordan']
})
.art 文件 其实就是 html 格式的文件