pug.compile()找不到模板文件(res.render()可以)

时间:2017-10-19 12:39:48

标签: node.js express pug

我正在编写一个小型NodeJS / Express应用程序。我将pug设置为模板引擎:

const app = express();

app.set('view engine', 'pug');
app.set('views', __dirname + "/public/views");
app.use(express.static(__dirname + '/public/static'));

调用res.render()发送HTML响应时,此方法正常:

app.get('/', function getIndex(req, res){
    res.render('index.pug');
});

但是当我尝试渲染小组件并将它们收集在字符串或数组中作为对AJAX调用的响应时,我无法使其工作。

const pug = require('pug');
const compile = pug.compileFile('option.pug');

这总是导致Error: ENOENT: no such file or directory, open 'option.pug'。我尝试将路径更改为路由器的透视图(类似于../../public/views/option.pug),但这也无济于事。

我不知道为什么路径的解释会有所不同。

使用pug.compileFile时如何引用此模板?

1 个答案:

答案 0 :(得分:3)

从Pug源代码中,传递的路径在选项中设置为filename

https://github.com/pugjs/pug/blob/926f7c720112cac76cfedb003e25e9f43d3a1767/packages/pug/lib/index.js#L354

然后将其传递给handleTemplateCache以读取文件:

https://github.com/pugjs/pug/blob/926f7c720112cac76cfedb003e25e9f43d3a1767/packages/pug/lib/index.js#L215

所以最终路径被传递给fs.readFileSync,它将相对路径视为相对于当前工作目录process.cwd()

您可以使用以下内容生成相应的路径:

const file = app.get('views') + '/option.pug';

最好使用path.join而不是字符串连接来构建路径,https://nodejs.org/api/path.html#path_path_join_paths

const path = require('path');
const file = path.join(app.get('views'), 'option.pug');

如果您不想(或不能)使用app.get('views'),您可以通过其他方式构建绝对路径,例如直接使用__dirname

另请注意,您可以将回调传递给res.render,该回调将传递呈现的HTML而不是将其写入响应。这可能会让您避免直接调用模板。