- 模板引擎
- 作用:
渲染产生HTML
替换HTML的数据内容
通过模板引擎的模板继承功能或模板包含功能实现页面的复用(如页头、页脚)
- 常用的模板引擎
Ejs模板引擎
Jade模板引擎
Swing模板引擎
例子:
Dir.js
const http = require('http');
const fs = require('fs');
// 创建服务
const server = http.createServer(function (req,res) {
if (req.url === '/favicon.ico'){
return;
}
fs.readFile('./index.html',function (err,htmlData) {
if (err) throw err;
// 读取txt文件中的内容(数据库操作)
fs.readFile('./data.txt',function (err,data) {
if (err) throw err;
//数组:[ '锄禾日当午,', '汗滴禾下土,', '谁知盘中餐,', '粒粒皆辛苦。' ]
const nameList = data.toString().split('\r\n');
// 替换模板内容(index.html称之为模板)
let template = htmlData.toString().replace('<%=$name1%>',nameList[0])
.replace('<%=$name2%>',nameList[1])
.replace('<%=$name3%>',nameList[2])
.replace('<%=$name4%>',nameList[3]);
res.writeHead(200,{
'Content-type':'text/html;charset=utf8'
});
res.end(template);
});
});
});
server.listen(8086,function () {
console.log('http server is running on port 8086');
})
Index.html:
<p>我的主题网页</p>
<h2>内容</h2>
<ul>
<li><%=$name1%></li>
<li><%=$name2%></li>
<li><%=$name3%></li>
<li><%=$name4%></li>
</ul>
Data.txt
锄禾日当午,
汗滴禾下土,
谁知盘中餐,
粒粒皆辛苦。