2

我有一个简单的应用程序应该输出一个小内容。我使用NodeJs、Express 和 Pug

const pug = require('pug');
const express = require('express');
const app = express();

const indexFile = 'index'; // the file to load

app.set('view engine', 'pug'); // use pug

app.get('/', function (req, res) {
  res.render(indexFile, { templateToLoad: 'Views/Templates/temp.pug' }); // include a template file
});

app.listen(8888, function () {
  console.log('Server running on port 8888');
});

还有我的 Pug 文件/HTML

doctype html
html
    body
      p default content on all pages
      include templateToLoad

我的目录看起来像这样

目录

启动服务器时,我收到此错误消息

Error: ENOENT: no such file or directory, open 'C:\Users\mah\Desktop\Test\views\templateToLoad.pug'
    at C:\Users\mah\Desktop\Test\views\index.pug line 5
    at Object.fs.openSync (fs.js:584:18)
    at Object.fs.readFileSync (fs.js:491:33)
    at Function.read (C:\Users\mah\Desktop\Test\node_modules\pug-load\index.js:69:13)
    at Object.read (C:\Users\mah\Desktop\Test\node_modules\pug\lib\index.js:147:25)
    at C:\Users\mah\Desktop\Test\node_modules\pug-load\index.js:24:25
    at walkAST (C:\Users\mah\Desktop\Test\node_modules\pug-walk\index.js:23:18)
    at C:\Users\mah\Desktop\Test\node_modules\pug-walk\index.js:104:20
    at Array.reduce (native)
    at walkAndMergeNodes (C:\Users\mah\Desktop\Test\node_modules\pug-walk\index.js:103:18)
    at walkAST (C:\Users\mah\Desktop\Test\node_modules\pug-walk\index.js:37:19)

但是在调试时templateToLoad我得到了'Views/Templates/temp.pug'. 为什么文件夹Templates会被忽略?

4

3 回答 3

2

Pug 提出模板继承https://pugjs.org/language/inheritance.html

因此,您无需渲染 index.pug,而是渲染您的模板:

指数.pug:

doctype html
html
  body
    p default content on all pages
    block content

temp.pug:

extends index.pug
block content
  p My template

你的 server.js

app.get('/', function (req, res) {
  res.render('temp');
});
于 2017-11-21T10:24:53.677 回答
2

是否进行了一些挖掘 - 哈巴狗似乎不支持动态包含(您在此处尝试执行此操作)

https://github.com/pugjs/pug/issues/569

可能的解决方法包括使用jade.render或重新使用res.renderwith 本身来生成模板。

于 2017-11-21T09:59:12.317 回答
2

pug不支持动态包含。我建议您在 index.pug 中发送模板名称并使用条件来显示所需的模板。

注意:temp1temp2...tempN需要存在于您的Templates文件夹中

doctype html
html
    body
      p default content on all pages
      if templateToLoad == "temp1"
        include Templates/temp
      else if templateToLoad == "temp2"
        include Templates/temp2

发送模板名称。

app.get('/', function (req, res) {
  res.render(indexFile, { templateToLoad: 'temp1' }); // include a template file
});
于 2017-11-21T09:59:27.360 回答