如何在Express App的视图中使用文件夹 [英] How to use folders in views with express app

查看:52
本文介绍了如何在Express App的视图中使用文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的views文件夹中的pug模板位于 views/administration/assets/fixed-assets.pug

I have a pug template inside my views folder under views/administration/assets/fixed-assets.pug

fixed-assets.pug 所源自的我的 default.pug 位于我的根视图文件夹中.

My default.pug which the fixed-assets.pug extends from is in my root views folder.

当我尝试呈现 fixed-assets.pug 视图时,它会在 views/administration/assets/中查找 default.pug >目录,而不是视图目录本身

When I try to render the fixed-assets.pug view it looks for the default.pug inside the views/administration/assets/ directory rather than the views directory itself

如果我采用 fixed-assets.pug 并将其放置在views目录中,而不是 views/administration/assets/目录中,则一切正常,并更新路由

Everything works fine if I take the fixed-assets.pug and place it in the views directory instead of the views/administration/assets/ directory and update the route accordingly.

如何告诉Express在views目录中查找 default.pug ,并在 views/administration/assets中查找 fixed-assets.pug /目录?

How can I tell express to look for the default.pug in the views directory and the fixed-assets.pug in the views/administration/assets/ directory?

这是我的路线

var express = require('express');
var secured = require('../lib/middleware/secured');
var router = express.Router();

/* GET fixed-assets page. */
router.get('/administration/fixed-assets', secured(), function(req, res, next) {
  res.render('administration/assets/fixed-assets', {
    title: 'Fixed Assets'
  });
});

module.exports = router;

这是我的 views/administration/assets/fixed-assets.pug

extends default.pug

block scripts
  if !starter
    script(src='/js/main.js')

block view
  .animated.fadeIn
    h1 Fixed Assets

这是我遇到的错误

ENOENT:没有这样的文件或目录,请打开'/usr/src/app/views/administration/assets/default.pug'在/usr/src/app/views/administration/assets/fixed-assets.pug第1行

ENOENT: no such file or directory, open '/usr/src/app/views/administration/assets/default.pug' at /usr/src/app/views/administration/assets/fixed-assets.pug line 1

感谢您的帮助!

推荐答案

在文档中,用于包含它说:

如果路径是绝对路径(例如,包含/root.pug),则通过以下方式解析在options.basedir之前.否则,路径将相对于当前正在编译的文件.

If the path is absolute (e.g., include /root.pug), it is resolved by prepending options.basedir. Otherwise, paths are resolved relative to the current file being compiled.

有关说明,请参见 API参考:

basedir:string所有绝对包含的根目录.

basedir: string The root directory of all absolute inclusion.

您可以在主app.js/server.js文件中像这样全局地实现basedir:

You can implement basedir globally like this in your main app.js/server.js file:

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.locals.basedir = path.join(__dirname, 'views');

这篇关于如何在Express App的视图中使用文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆