admin管理员组文章数量:1278983
I would like to use EJS as my template engine in NestJS. With Express I can configure EJS in the main file like this:
app.set("view engine", "ejs");
How can I best implement this with NestJS? Nestjs does not ship with a .set
method.
I would like to use EJS as my template engine in NestJS. With Express I can configure EJS in the main file like this:
app.set("view engine", "ejs");
How can I best implement this with NestJS? Nestjs does not ship with a .set
method.
1 Answer
Reset to default 9You can configure that with the help of app.setViewEngine('ejs')
in main.ts
. First, install it:
npm i ejs
With the lines below, you would have told Express that the public
directory will be used for storing static assets, views
will contain templates, and the ejs
template engine should be used to render HTML output.
// 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();
And below is how you would render a template in a Controller. You are rendering index.ejs
and passing message
as a parameter.
// app.controller.ts
import { Get, Controller, Render } from '@nestjs/mon';
@Controller()
export class AppController {
@Get()
@Render('index')
root() {
return { message: 'Hello world!' };
}
}
Finally, you would use that passed message
variable inside index.ejs
like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>App</title>
</head>
<body>
<%= message %>
</body>
</html>
You can read more on the official documentation.
本文标签: javascriptHow to use EJS template engine with NestJSStack Overflow
版权声明:本文标题:javascript - How to use EJS template engine with NestJS? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741282788a2370103.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论