Express.js – app.render() 方法


app.render() 方法用於使用回撥函式返回檢視的已呈現 HTML。此方法接受一個可選引數,它是一個包含 view 的區域性變數的物件。

此方法與 res.render() 函式類似,區別在於它不能將已呈現檢視傳送給客戶端/使用者本身。


語法

app.render(view, [locals], callback)

示例

建立一個名為 "appRender.js" 的檔案並複製以下程式碼片段。建立檔案後,使用命令 "node appRender.js" 來執行此程式碼。

// app.render() Method Demo Example

// Importing the express module
const express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Setting up the view engine
app.set('view engine', 'ejs');

// Rendering the email.ejs content from view
app.render('email', function (err, html) {
   if (err) console.log(err);
   console.log(html);
});

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

email.ejs

現在,建立檔案 "email.ejs" 並將其儲存在 views 資料夾中。

<html>
<head>
   <title>Welcome to Tutorials Point</title>
</head>
<body>
   <h3>SIMPLY LEARNING</h3>
</body>
</html>

輸出

C:\home
ode>> node appRender.js <html> <head> <title>Welcome to Tutorials Point</title> </head> <body> <h3>SIMPLY LEARNING</h3> </body> </html> Server listening on PORT 3000

更新時間: 2021 年 9 月 30 日

2K+瀏覽量

啟動你的 職業

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.