Ale*_*erg 3 javascript ejs node.js typescript nestjs
我想在 NestJS 中使用 EJS 作为模板引擎。使用 Express,我可以在主文件中配置 EJS,如下所示:
app.set("view engine", "ejs");
Run Code Online (Sandbox Code Playgroud)
我怎样才能最好地用 NestJS 实现这个?Nestjs 不附带.set方法。
app.setViewEngine('ejs')您可以在in的帮助下进行配置main.ts。首先,安装它:
npm i ejs
Run Code Online (Sandbox Code Playgroud)
通过下面的行,您将告诉 Express 该public目录将用于存储静态资源,views将包含模板,并且ejs模板引擎应用于呈现 HTML 输出。
// main.ts
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
);
/*
Here it's assumed that public and views are in the root directory,
alongside src. You can put them wherever you want,
just use the correct path if you use another folder.
*/
app.useStaticAssets(join(__dirname, '..', 'public'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('ejs');
await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
下面是如何在控制器中渲染模板。您正在渲染index.ejs并message作为参数传递。
// app.controller.ts
import { Get, Controller, Render } from '@nestjs/common';
@Controller()
export class AppController {
@Get()
@Render('index')
root() {
return { message: 'Hello world!' };
}
}
Run Code Online (Sandbox Code Playgroud)
最后,您将在内部使用传递的message变量,index.ejs如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App</title>
</head>
<body>
<%= message %>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您可以阅读官方文档了解更多内容。
| 归档时间: |
|
| 查看次数: |
7572 次 |
| 最近记录: |