推荐答案
在 Fastify 中使用 EJS 模板引擎的步骤如下:
安装依赖: 首先需要安装
fastify和point-of-view插件,以及ejs模板引擎。npm install fastify point-of-view ejs
配置 Fastify: 在 Fastify 应用中注册
point-of-view插件,并配置 EJS 作为模板引擎。// www.javascriptcn.com code example const fastify = require('fastify')({ logger: true }); fastify.register(require('point-of-view'), { engine: { ejs: require('ejs') } }); fastify.get('/', (req, reply) => { reply.view('/templates/index.ejs', { text: 'Hello, Fastify with EJS!' }); }); fastify.listen(3000, (err) => { if (err) { fastify.log.error(err); process.exit(1); } fastify.log.info('Server is running on http://localhost:3000'); });创建 EJS 模板: 在项目根目录下创建
templates文件夹,并在其中创建index.ejs文件。// www.javascriptcn.com code example <!-- templates/index.ejs --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fastify with EJS</title> </head> <body> <h1><%= text %></h1> </body> </html>
运行应用: 启动 Fastify 应用,访问
http://localhost:3000,你将看到渲染后的 EJS 模板内容。
本题详细解读
1. 安装依赖
在 Fastify 中使用 EJS 模板引擎,首先需要安装 fastify 作为 Web 框架,point-of-view 插件用于支持模板引擎,以及 ejs 作为具体的模板引擎。
npm install fastify point-of-view ejs
2. 配置 Fastify
在 Fastify 应用中,通过 point-of-view 插件来集成 EJS 模板引擎。point-of-view 插件允许你使用多种模板引擎,包括 EJS、Pug、Handlebars 等。
fastify.register(require('point-of-view'), {
engine: {
ejs: require('ejs')
}
});3. 创建 EJS 模板
EJS 模板文件通常放在项目的 templates 目录下。在模板文件中,你可以使用 EJS 的语法来动态生成 HTML 内容。
// www.javascriptcn.com code example <!-- templates/index.ejs --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fastify with EJS</title> </head> <body> <h1><%= text %></h1> </body> </html>
4. 渲染模板
在路由处理函数中,使用 reply.view 方法来渲染 EJS 模板,并传递数据给模板。
fastify.get('/', (req, reply) => {
reply.view('/templates/index.ejs', { text: 'Hello, Fastify with EJS!' });
});5. 运行应用
启动 Fastify 应用后,访问 http://localhost:3000,你将看到渲染后的 EJS 模板内容。
node app.js
通过以上步骤,你可以在 Fastify 中成功使用 EJS 模板引擎来渲染动态内容。