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.