nestjs框架中使用nunjucks模板引擎
main.ts
import { NestFactory } from '@nestjs/core';
import {
ExpressAdapter,
NestExpressApplication,
} from '@nestjs/platform-express';
import { AppModule } from './app.module';
import nunjucks = require('nunjucks');
import { join } from 'path';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
new ExpressAdapter(),
);
app.useStaticAssets(join(__dirname, '..', 'public')); // NestFactory.create需要加泛型参数<NestExpressApplication>
app.setBaseViewsDir(join(__dirname, '..', 'views')); // 修改模板文件后立马生效,否则需要重启服务,nunjucks watch参数也有相同作用
nunjucks.configure('views', {
ext:'njk',
autoescape: true,
express: app,
watch: true,
});
await app.listen(3000, () => {
});
}
bootstrap();
app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('articles')
// @Render('articles.njk') // 不能使用@Render装饰器,而是使用res.render
async findArticlesByUser(@Res() res:Response): Promise<any> {
return res.render('articles.njk', {
title: "标题",
articles
})
}
}
articles.njk
<ul>
{% for item in articles %}
<li>{{ item.title }}</li>
{% endfor %}
</ul>