用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部分:
Document
#
商品名称
商品价格
<% arra.forEach(item=>{%>
<%= item.pid%>
<%= item.pname%>
<%= item.price%>
<%})%>