推荐答案
在 Express 中渲染模板通常使用 res.render() 方法。以下是一个简单的示例:
// www.javascriptcn.com code example
const express = require('express');
const app = express();
const path = require('path');
// 设置模板引擎
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
// 定义路由
app.get('/', (req, res) => {
res.render('index', { title: 'Express Template Rendering', message: 'Hello, World!' });
});
// 启动服务器
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});在这个示例中,我们使用了 Pug 作为模板引擎,并通过 res.render() 方法渲染了 index.pug 模板文件,同时传递了一个包含 title 和 message 的对象作为模板的上下文数据。
本题详细解读
1. 设置模板引擎
在 Express 中渲染模板之前,首先需要设置模板引擎。常见的模板引擎有 Pug、EJS、Handlebars 等。通过 app.set('view engine', 'pug') 设置模板引擎为 Pug,并通过 app.set('views', path.join(__dirname, 'views')) 指定模板文件的存放目录。
2. 使用 res.render() 方法
res.render() 是 Express 中用于渲染模板的方法。它接受两个参数:
- 第一个参数是模板文件的名称(不包括扩展名),例如
index。 - 第二个参数是一个对象,包含传递给模板的上下文数据。
3. 模板文件
模板文件通常存放在 views 目录下。例如,index.pug 文件内容可能如下:
html
head
title= title
body
h1= message在这个模板中,title 和 message 是从 res.render() 方法传递过来的数据。
4. 启动服务器
最后,通过 app.listen() 方法启动服务器,监听指定的端口(如 3000),并在浏览器中访问 http://localhost:3000 查看渲染后的页面。
通过以上步骤,你可以在 Express 中成功渲染模板并显示动态内容。