node.js - 在 NestJS 中为 Pug 设置“basedir”选项
问题描述
我正在尝试在 中使用pug
布局NestJS
,但是当从绝对路径扩展布局时,pug
需要basedir
设置该选项。
在 ExpressJS 中你会使用app.locals.basedir = ...
,在 NestJS 中什么是等价的?
const server = await NestFactory.create<NestExpressApplication>(AppModule);
server.setViewEngine('pug');
server.setBaseViewsDir(join(__dirname, 'templates', 'views'));
await server.listen(config.server.port);
在视图中使用extends /layouts/index
会抛出以下内容;the "basedir" option is required to use includes and extends with "absolute" paths
.
我不想使用相对路径,因为这很快就会变得非常混乱。例如extends ../../../layouts/index
解决方案
据我所知,您可以实现/layouts/index
与仅使用目录layout/index
中layout
的文件夹相同的功能templates/views
。
我已经建立了一个 git repo作为一个工作示例,这样你就可以自己测试它,看看我是否需要更深入地了解任何事情。
编辑2019 年 6 月 27 日:
谢谢,我误解了你最初的问题。
使用基于创建和表达的应用程序,您可以发送一个express server
以NestFactory
使用该服务器实例,而不是让 Nest 为您创建一个普通实例。从这里您可以express server
像往常一样设置并获得所需的功能。我已经修改了 git repo 以便能够更好地测试场景并相信这就是您要寻找的。
我的main.ts
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication, ExpressAdapter } from '@nestjs/platform-express';
import * as express from 'express';
import { AppModule } from './app.module';
import { join } from 'path';
async function bootstrap() {
// Creating and setting up the express instanced server
const server = express();
server.locals.basedir = join(__dirname, '..', 'views');
// Using the express server instance in the nest factory
const app = await NestFactory.create<NestExpressApplication>(AppModule, new ExpressAdapter(server));
app.useStaticAssets(join(__dirname, '..', 'public'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('pug');
await app.listen(3000);
}
bootstrap();
总的来说文件夹设置是这样的
src
|-app.controller.ts
|-app.module.ts
|-app.service.ts
|-main.ts
views
|-hello
|-home.pug
|-message
|-message.pug
|-templates
|-layout.pug
我home.pug
和message.pug
文件的开头是extends /templates/layout
推荐阅读
- jupyter - Jupyter Notebook 不吃午饭
- c - 如何将 haskell [char] 转换为 CString
- python-3.x - Python 3 保存文件时出错,由不同的程序打开它并比较列表值
- javascript - Chrome 扩展程序说“阅读您的浏览历史记录”,即使它没有
- java - 如何在java中替换每个字符
- reactjs - 将 JSON 响应绑定到数组时出错 - React
- python - 如何使用networkx绘制流向箭头?
- python - 在 Django 中显示史诗和任务
- javascript - 如何仅通过属性将两个对象分配给一个对象
- laravel - laravel 刀片 @auth 和 @guest