如何在nestjs框架中使用nunjucks模板?

avi*_*ang 3 node.js nestjs

如何正确使用 NestExpressApplication 下的 nunjucks 模板?

ego*_*mkn 5

对于那些想要将Nunjucks模板引擎与NestJS框架一起使用并发现这个问题的人,这里是一个最小的示例:

import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as nunjucks from 'nunjucks';
import * as path from 'path';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  const express = app.getHttpAdapter().getInstance();

  const assets = path.join(__dirname, '..', 'assets'); // Directory with static HTML/CSS/JS/other files
  const views = path.join(__dirname, '..', 'views'); // Directory with *.njk templates

  nunjucks.configure(views, { express });
  
  app.useStaticAssets(assets);
  app.setBaseViewsDir(views);
  app.setViewEngine('njk');

  await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)