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

时间:2019-05-09 10:18:40

标签: node.js nestjs

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

2 个答案:

答案 0 :(得分:0)

import { join } from "path";
import { NestFactory } from "@nestjs/core";
import { NestExpressApplication } from "@nestjs/platform-express";
import * as nunjucks from "nunjucks";
import * as helmet from "helmet";
import { ApplicationModule } from "./app.module";

async function bootstrap() {
  let options: any = {};
  if (process.env.NODE_ENV === "product") options.logger = false;

  const app = await NestFactory.create<NestExpressApplication>(
    ApplicationModule,
    options
  );

  app.use(helmet());
  // app.useGlobalPipes(
  //   new ValidationPipe({
  //     whitelist: true,
  //     validationError: { target: false, value: false },
  //   }),
  // );
  app.useStaticAssets(join(__dirname, "..", "public"), { prefix: "/static/" });

  const environment = nunjucks.configure(
    [
      join(__dirname, "..", "template"),
      join(__dirname, ".", "system_template")
    ],
    {
      autoescape: true,
      throwOnUndefined: false,
      trimBlocks: false,
      lstripBlocks: false,
      watch: true,
      noCache: process.env.NODE_ENV === "local" ? true : false,
      express: app
    }
  );
  app.engine("njk", environment.render);
  app.setViewEngine("njk");
  app.set("view cache", true);

  await app.listen(process.env.APP_PORT);
}

bootstrap();

答案 1 :(得分:0)

对于那些想在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();