推荐答案
在 Fastify 中使用模板引擎非常简单,可以通过 fastify-view 插件来实现。以下是一个使用 ejs 模板引擎的示例:
// www.javascriptcn.com code example
const fastify = require('fastify')({ logger: true });
const path = require('path');
// 注册 fastify-view 插件
fastify.register(require('@fastify/view'), {
engine: {
ejs: require('ejs'),
},
root: path.join(__dirname, 'views'), // 指定模板文件所在的目录
});
// 定义一个路由来渲染模板
fastify.get('/', (req, reply) => {
reply.view('index.ejs', { title: 'Fastify with EJS', message: 'Hello, Fastify!' });
});
// 启动服务器
fastify.listen({ port: 3000 }, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
});在这个示例中,我们使用了 ejs 作为模板引擎,并通过 reply.view 方法来渲染模板文件 index.ejs,同时传递了一些数据给模板。
本题详细解读
1. 安装依赖
首先,你需要安装 fastify 和 @fastify/view 插件,以及你选择的模板引擎(如 ejs):
npm install fastify @fastify/view ejs
2. 注册插件
在 Fastify 中,模板引擎的使用是通过 @fastify/view 插件来实现的。你需要注册这个插件,并指定使用的模板引擎和模板文件所在的目录。
fastify.register(require('@fastify/view'), {
engine: {
ejs: require('ejs'),
},
root: path.join(__dirname, 'views'),
});engine:指定模板引擎及其对应的模块。root:指定模板文件所在的目录。
3. 定义路由并渲染模板
在路由处理函数中,你可以使用 reply.view 方法来渲染模板文件,并传递数据给模板。
fastify.get('/', (req, reply) => {
reply.view('index.ejs', { title: 'Fastify with EJS', message: 'Hello, Fastify!' });
});index.ejs:模板文件的名称。{ title: 'Fastify with EJS', message: 'Hello, Fastify!' }:传递给模板的数据。
4. 模板文件
在 views 目录下创建一个 index.ejs 文件,内容如下:
// www.javascriptcn.com code example <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><%= title %></title> </head> <body> <h1><%= message %></h1> </body> </html>
在这个模板文件中,我们使用了 ejs 的语法 <%= %> 来输出传递过来的数据。
5. 启动服务器
最后,启动 Fastify 服务器:
fastify.listen({ port: 3000 }, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
});访问 http://localhost:3000,你将看到渲染后的页面。