在Jade中渲染单个块

5
我正在使用Node.js和Express。假设我有一对Jade文件:
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

example-content.jade

p
  | Lorem ipsum yadda yadda

但是这样创建额外的文件似乎有些粗糙。
1个回答

0
Jade 支持可执行代码。当使用前缀 -(无缓冲)时。例如,您可以在主布局 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);

我想没有办法有条件地包含“extends模板”行;在我的模板文件中放置两个巨大的if块似乎很痛苦。 - Retsam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接