node.js中使用ejs渲染數(shù)據(jù)的代碼實現(xiàn)
用ejs模板引擎講面的數(shù)據(jù)渲染到頁面的表格中
[
{"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模塊
第三步 : 判斷路由 根據(jù)訪問不同的路由 渲染不同的ejs模板引擎
如何渲染ejs模板引擎?
ejs.renderFile( "路徑" , {數(shù)據(jù)} ,(err,data)=>{
} )
代碼實現(xiàn):
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},
]
//創(chuàng)建服務器
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("服務器已經(jīng)啟動")
}) 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渲染數(shù)據(jù)的文章就介紹到這了,更多相關node.js ejs渲染數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
nodejs版本過高導致vue-cli項目無法正常運行的幾種解決方案
這篇文章主要給大家介紹了關于nodejs版本過高導致vue-cli項目無法正常運行的幾種解決方案,在項目中你可能需要用到的node版本太低,但是你所下的node版本是最新的,這時候就會報錯,需要的朋友可以參考下2023-07-07
package-lock.json解決依賴的版本管理使用詳解
這篇文章主要為大家介紹了package-lock.json解決依賴的版本管理使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08

