Nodejs中如何使用模板引擎?如何使用模板引擎渲染HTML?
使用readdir获取指定路径下的所有文件名
文件结构
实现代码
const fs = require('fs');
fs.readdir('G:/pink_code/Node_Study/02',(err,list) => {
if (!err) {
console.log(list);
}
})
代码输出
[ '01_http-helloWorld.js', '02_使用readdir获取指定路径下的所有文件名.js', 'www' ]
在浏览器中使用模板引擎
1. 安装art-template
npm install art-template
2. 通过script标签引入art-template
3. 使用模板引擎语法进行调用
在Node中使用模板引擎
1. 安装art-template
npm install art-template
2. 在需要使用模板引擎的模块中加载art-template
3. 查文档,使用模板引擎的API
在Node中使用模板引擎的一个小案例
const template = require('art-template');
const test = template.render('hello {{name}}',{
name: 'NodeJs'
})
console.log(test);
输出结果
hello NodeJs
一个使用模板引擎渲染HTML的小案例
HTML结构
C:/Users/HP/Desktop/共享文件/ 的索引
C:/Users/HP/Desktop/共享文件/ 的索引
| 名称 | 大小 | 修改日期 |
|---|---|---|
| {{$value}} | 189 kB | 2021/7/28 下午5:36:03 |
Node代码
const http = require('http');
const template = require('art-template');
const fs = require('fs');
const server = http.createServer();
server.on('request', (req, res) => {
const url = req.url;
// 文件路径
const filePath = 'G:/pink_code/Node_Study/02';
// 获取文件路径下所有的文件名
let listName;
fs.readdir(filePath, (err, list) => {
if (!err) {
listName = list;
}
})
// 读取模板文件内容
fs.readFile('./www/template.html', (err, data) => {
if (!err) {
data = data.toString();
test = template.render(data,{
files: listName
})
res.end(test);
} else {
console.log('读取文件出错', err);
}
});
})
// 监听3000端口
server.listen(3000, (err) => {
if (!err) {
console.log('服务器启动成功!');
}
})
以上就是Nodejs中如何使用模板引擎?如何使用模板引擎渲染HTML?的详细内容,更多请关注毛票票其它相关文章!