【问题标题】:using common layout for all the pages in pug对 pug 中的所有页面使用通用布局
【发布时间】:2017-09-21 20:52:47
【问题描述】:

我正在尝试使用 express 的哈巴狗

views/layout.pug 

doctype html
html
  head
    title= title
    link(rel="shortcut icon", href="favicon.ico", type="image/x-icon")
    link(rel='stylesheet', href='/assets/application.css')
    link(rel='stylesheet', href="assets/libs/bootstrap/dist/css/bootstrap.min.css")
  body    
    script(src="assets/libs/jquery/dist/jquery.min.js")
    script(src='assets/libs/bootstrap/dist/js/bootstrap.min.js')
    script(src="assets/application.js")
    block content

这是用户页面的路由器。

routes/user.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('user/index');
});

module.exports = router;

我对用户/索引页面有自己的看法。我从视图中扩展了布局。使用布局的用户索引页面。 layout.pug 存在于 views 文件夹中。

如果我在视图/用户中添加一个 layout.pug,它就可以工作。但是如何使用views/layout.pug

/views/user/index.pug

extends layout


block content
    h1
     | User index

我收到以下错误。它正在视图/用户文件夹中寻找布局。如何让它使用 view/layout.pug。

Error: ENOENT: no such file or directory, open 'C:\my_projects\myexpressapp\views\user\layout.pug'
    at C:\my_projects\myexpressapp\views\user\index.pug line 1
    at Error (native)
    at Object.fs.openSync (fs.js:640:18)
    at Object.fs.readFileSync (fs.js:508:33)
    at Function.read (C:\my_projects\myexpressapp\node_modules\pug-load\index.js:69:13)
    at Object.read (C:\my_projects\myexpressapp\node_modules\pug\lib\index.js:147:25)
    at C:\my_projects\myexpressapp\node_modules\pug-load\index.js:24:25
    at walkAST (C:\my_projects\myexpressapp\node_modules\pug-walk\index.js:23:18)
    at C:\my_projects\myexpressapp\node_modules\pug-walk\index.js:104:20
    at Array.reduce (native)
    at walkAndMergeNodes (C:\my_projects\myexpressapp\node_modules\pug-walk\index.js:103:18)

【问题讨论】:

  • 正如错误所说,文件 layout.pug 不在正确的导入位置
  • 如果在视图/用户中添加一个 layout.pug 就可以了。但是如何使用views/layout.pug
  • 试试extends ../layout
  • 非常感谢它的工作:)

标签: javascript node.js express pug


【解决方案1】:

在您的app.js 文件中,检查您是否正确定义了视图。

应将视图引擎设置为 pug,并应正确设置视图文件夹,如下所述app.js

app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));

【讨论】:

    【解决方案2】:

    【讨论】:

    • app.set('views', path.join(__dirname, 'views'));我的 server.js 中有。
    • 你试过这个app.locals.basedir = app.get('views'); 吗?设置好变量后,可以使用extends /layoutpas 必须以“/”开头
    猜你喜欢
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多