NodeJs使用ejs模板引擎实现后端渲染

时间:2022-07-24
本文章向大家介绍NodeJs使用ejs模板引擎实现后端渲染,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

安装ejs

npm install ejs

项目引入

const ejs = require('ejs') 

目录文件

app.js

const http = require('http');
const url = require('url')
const ejs = require('ejs')
http.createServer((req, res) => {
    // 路由
    let pathname = url.parse(req.url).pathname;
    if (pathname == '/login') {
        // 假设定义从服务器请求的数据
        let msg = "数据库里面获取的数据"
        let list = [{
            title: '新闻111'
        }, {
            title: '新闻222'
        }, {
            title: '新闻333'
        }, ]
        ejs.renderFile('./views/login.ejs', {
            msg: msg,
            list: list
        }, (err, data) => {
            res.writeHead(200, {
                'Content-Type': 'text/html;charset="utf-8"'
            });
            res.end(data)
        })
    }

}).listen(8081);

login.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h3><%=msg%></h3>
    <ul>
        <%for(let i in list) {%>
        <li><%= list[i].title%></li>
        <%}%>
    </ul>
</body>
</html>