nestjs框架中使用nunjucks模板引擎

  • 分类:【Nodejs
  • 浏览【425】
  • 评论【0】
  • 更新【2019-4-30 16:31:18】

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(
        AppModule,
        new ExpressAdapter(),
    );
    app.useStaticAssets(join(__dirname + '/public')); // NestFactory.create需要加泛型参数
    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 {
        return res.render('articles.njk', {
            title: "标题",
            articles
        })
    }
}

articles.njk

    {% for item in articles %}
  • {{ item.title }}
  • {% endfor %}

关键字词:nestjs,nunjucks