Node.js-模板引擎

  1. 模板引擎
  • 作用:

          渲染产生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

锄禾日当午,
汗滴禾下土,
谁知盘中餐,
粒粒皆辛苦。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值