渲染单块玉石

时间:2013-08-05 04:08:39

标签: javascript node.js templates express pug

我正在使用Node.js并表达。假设我有一对玉文件:

template.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来加载这些文件(好吧,显然不是这些文件),当这样做时,我想要一个只返回页面内容的请求 - 内容块本身,没有完整的html文档的其余部分。有没有一种简单的方法可以告诉Jade只是渲染块本身而不是将其嵌入到模板中?


我能想到的最好的就是改变它:

example.jade

extends template
  block page-content
    import example-content

例如-content.jade

p
  | Lorem ipsum yadda yadda

但是创建像这样的额外文件似乎很苛刻。

1 个答案:

答案 0 :(得分:0)

Jade支持可执行代码。使用前缀时 - (不缓冲)。例如,您可以在主布局jade模板中使用 if statment

- 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:*

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

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

app.use(logger);
相关问题