node.js中使用ejs渲染数据的代码实现

 更新时间:2023年11月11日 16:13:31   作者:万物得其道者成  
这篇文章主要介绍了node.js中使用ejs渲染数据,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

用ejs模板引擎讲面的数据渲染到页面的表格中       

 [
    {"pid":1,"pname":"小米1","price":2888},
    {"pid":2,"pname":"小米2","price":3888},
    {"pid":3,"pname":"小米3","price":4888},
    {"pid":4,"pname":"小米4","price":5888},
    {"pid":5,"pname":"小米5","price":6888},
]

ejs模板引擎的使用       

        第一步 : ejs的安装   npm i ejs

        第二步 : 导入ejs模块

        第三步  : 判断路由  根据访问不同的路由 渲染不同的ejs模板引擎

        如何渲染ejs模板引擎?

        ejs.renderFile( "路径" , {数据}  ,(err,data)=>{

    } )

代码实现:

        js部分:

    const http = require("http")
const url = require("url")
const ejs = require("ejs")
let arr = [
	{"pid":1,"pname":"小米1","price":2888},
	{"pid":2,"pname":"小米2","price":3888},
	{"pid":3,"pname":"小米3","price":4888},
	{"pid":4,"pname":"小米4","price":5888},
	{"pid":5,"pname":"小米5","price":6888},
]
//创建服务器
http.createServer((req,res)=>{
    //查找路由
    let pathname = url.parse(req.url).pathname
    if(pathname == "/home"){
        //渲染ejs模板引擎
        ejs.renderFile("./index.ejs",{arra:arr},(err,data)=>{
            res.end(data)
        })
    }
}).listen(3002,()=>{ //启动服务器
    console.log("服务器已经启动")
})            

html部分:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <table border="1" cellapdding="20" cellspacing="0">
        <thead>
            <tr>
                <td>#</td>
                <td>商品名称</td>
                <td>商品价格</td>
            </tr>
        </thead>
        <tbody>
            <% arra.forEach(item=>{%>
                <tr>
                    <td><%= item.pid%></td>
                    <td><%= item.pname%></td>
                    <td><%= item.price%></td>
                </tr>  
            <%})%>
        </tbody>
    </table>
</body>
</html>

到此这篇关于node.js中使用ejs渲染数据的文章就介绍到这了,更多相关node.js ejs渲染数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论