PugJs的模板布局

时间:2018-09-25 12:50:14

标签: node.js pug

我将NodeJ与Handlebars一起使用,并考虑过切换到PugJ,因为某些功能是本机的-使用Handlebars需要一些辅助功能/部分。

在车把中,我必须定义一个布局并传入模板。在PugJs中,我创建了两个示例路线

第一个路由文件:

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

router.get('/', (req, res) => {
    res.render('index', {
        title: 'Home',
        template: 'main'
    });
});

module.exports = router;

第二条路线文件:

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

router.get('/', (req, res) => {
    res.render('index', {
        title: 'Page2',
        template: 'pageTwo'
    });
});

module.exports = router;

如您所见,我总是必须渲染索引文件并将所需的pug文件作为模板变量传递。

index.pug

doctype html
html
  include ./header.pug
  body
    include ./templates/#{template}.pug

header.pug

head
  title #{title} template!

main.pug

script(src='./client/main.js')
h1 main content here

pageTwo.pug

p pageTwo

渲染哈巴狗文件时出现此错误

  

ENOENT:没有这样的文件或目录,请打开   '... \ views \ templates \#{template} .pug'

如何用正确的模板变量替换#{template}

1 个答案:

答案 0 :(得分:2)

动态模板选择不是pug的功能,我认为它与pug如何将所有内容预编译为JavaScript函数有关,而JavaScript函数在运行时仍保留在node.js内。这样做的好处是超快速的页面呈现,因此我们很高兴继续使用pug并解决此问题。

说到这,您可以使用conditional logic完成您想做的事情:

doctype html
html
  include ./header.pug
  body
    if template === 'pageOne'
      include ./templates/pageOne.pug
    else if template === 'pageTwo'
      include ./templates/pageTwo.pug
    else
      include ./templates/home.pug

您还应该查看extends feature,以简化将标头添加到模板中的过程,以及mixins,以重新使用模板之间的代码。您可能会发现,通过重新设计,这些功能可以为您的需求提供更好的解决方案。