【问题标题】:Render single block in jade在翡翠中渲染单个块
【发布时间】:2013-08-05 16:55:28
【问题描述】:

我正在使用 Node.js 和 express。假设我有一对玉文件:

模板.jade

html
  body
    block page-content

example.jade

extends template
    block page-content
        p
           |  Lorem ipsum yadda yadda

如果我渲染 example.jade,我会得到将段落标签插入到 template.jade 的 body 标签中的结果,这通常是我想要的。

我的问题是我正在尝试使用 pushState 和 History API 来加载这些文件(好吧,显然不是 -这些文件),并且在这样做时,我想要一个只返回页面内容的请求-content 块本身,没有完整的 html 文档的其余部分。有没有一种简单的方法来告诉 Jade 只渲染块本身而不是将其嵌入到模板中?


我能想到的最好的办法就是把它改成:

example.jade

extends template
  block page-content
    import example-content

example-content.jade

p
  | Lorem ipsum yadda yadda

但是像这样创建额外的文件似乎很不自然。

【问题讨论】:

    标签: javascript node.js templates express pug


    【解决方案1】:

    Jade 支持可执行代码。当使用前缀 - (没有缓冲)。例如,您可以在主布局玉模板中使用 if 语句:

    - if (renderType && renderType == 'page') {
        doctype 5
        html
          head
            title= title
          body
    - }
            block content
    

    像这样渲染html页面:

      res.render('index', { title: 'StackOverflow', renderType: 'page' });
    

    像这样渲染 html 块:

      res.render('index', { title: 'StackOverflow', renderType: 'block' });
    

    如果您不喜欢在所有渲染表达式中使用 renderType 变量,请使用

    res.locals(obj) //*Assign several locals with the given obj. The following are equivalent:*
    

    并为所有请求设置默认值。 您在哪里初始化应用添加处理程序:

    var logger = function(req, res, next)
    {
        res.locals({renderType:'page'});
        next();
    };
    
    app.use(logger);
    

    【讨论】:

    • 我不认为有任何方法可以有条件地包含“扩展模板”行;在我的模板文件中放置两个巨大的 if 块似乎很痛苦。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2016-03-17
    相关资源
    最近更新 更多