art-template 模板引擎 目标: 将数组动态显示在网页上 const userList = [
{id:1, username: 'Jax', nickname: '武器大师', gender: 1},
{id:2, username: 'Lux', nickname: '光辉女郎', gender: 2},
{id:3, username: 'Ashe', nickname: '寒冰射手', gender: 2},
{id:4, username: 'Raze', nickname: '符文法师', gender: 1},
{id:5, username: 'Jinx', nickname: '暴走萝莉', gender: 2}
]
let str = ''
for (let i = 0; i < userList.length; i++) {
str += `
<tr>
<td>${userList.id}</td>
<td>${userList.username}</td>
<td>${userList.nickname}</td>
<td>${userList.gender}</td>
</tr>
`
}
document.querySelector('tbody').innerHTML = str
解决方案: 模板引擎
1 模板引擎介绍模板引擎的本质是一种字符串拼接技术 按照规则在模板页(网页)上挖坑,布置数据规则 再将数据和模板组合成一个字符串
常见的模板引擎:
2 art-template基本使用使用art-template模板引擎遵循以下步骤即可:
npm install art-template
const template = require('art-template');
js对象: {a: "Hello", b: "world"} json对象: {"a": "Hello", "b": "world"}
注意: 属性不加双引号或者加双引号均可,但是切忌不要加单引号。此处不会出错,但是其他的位置可能会出错。 html页面(模板页)上使用特殊标记({{key}}),将要显示数据的位置标记出来;此处的key就是js对象的属性
//参数1: 模板文件路径 --- 必须使用绝对路径
//参数2: 要显示出来的数据 --- js/json对象
//返回值: 数据和模板组装好的字符串
let htmlStr = template(var1, var2);
res.end(htmlStr);
简单案例:将 {name: "张三", age: 20, gender:"男"} npm install art-template==注意: 在哪里执行该命令,art-template就会下载到哪里==
模板页组装结构: 我叫{{name}},今年{{age}}岁,我是个{{gender}}生
3 循环结构 --- each{{each data value index}}
输出内容
{{/each}}
data: 要循环输出的数组
value: 单元值
index: 单元索引(一般不用)
注意: 使用 {{/each}} 结束循环
示例: // 调用 template 函数组装模板和数据
// 得到组装好的字符串保存在 str 中
const str = template(fpath, {data: [
{id:1, username: 'Jax', nickname: '武器大师', gender: 1},
{id:2, username: 'Lux', nickname: '光辉女郎', gender: 2},
{id:3, username: 'Ashe', nickname: '寒冰射手', gender: 2},
{id:4, username: 'Raze', nickname: '符文法师', gender: 1},
{id:5, username: 'Jinx', nickname: '暴走萝莉', gender: 2}
]})
<table width="500" align="center" border="1">
<thead>
<tr>
<th>编号</th>
<th>ID</th>
<th>姓名</th>
<th>昵称</th>
<th>性别</th>
</tr>
</thead>
<tbody>
{{each data value index}}
<tr>
<td>{{index}}</td>
<td>{{value.id}}</td>
<td>{{value.username}}</td>
<td>{{value.nickname}}</td>
<td>{{value.gender === 1 ? '男' : '女'}}</td>
</tr>
{{/each}}
</tbody>
</table>
4 if...else 结构只使用 if {{if 判断表达式}}
结果
{{/if}}
if...else {{if 判断表达式}}
结果1
{{else}}
结果2
{{/if}}
if...elseif...else {{if 判断表达式1}}
结果1
{{else if 判断表达式2}}
结果2
{{else if 判断表达式3}}
结果3
{{else}}
结果4
{{/if}}
示例: const data = {
name: 'zhangsan',
age: 10,
h: 10
}
const str = template(fpath, data)
{{if flag}}
这是真的
{{/if}}
<hr>
{{if age >= 18}}
成年人
{{else}}
未成年人
{{/if}}
<hr>
{{if h >= 0 && h < 6}}
凌晨好
{{else if h < 12}}
上午好
{{else if h < 18}}
下午好
{{else if h < 24}}
晚上好
{{else}}
时间错误
{{/if}}
|