Jade模板——动态调用Mixin

5
如何使用从json中传入的字符串动态加载mixin?下面的目标是让twoColumn.jade加载foobar mixin。

twoColumn.jade

mixin twoColumns(obj)
    .container-fluid
        .row(class=obj.class)
            for item in obj.items
                .col-xs-12.col-sm-3
                    //- Syntax for dynamically calling a mixin?
                    +item.template(item)

content.json

{
    "twoColumns": {
        "class": "foobar",
        "items": [
            {
                "template": "foo",
                "title": "Hello"     
            },
            {
                "template": "bar",
                "title": "World"     
            }
        ]            
    }
}
1个回答

8
这是一项在Jade中不太明显的功能,因为它在文档中没有明确提到。你实际上可以使用插值语法(#{...})来动态选择mixin名称。
Jade语言指南中得知:

interpolation? yup! both types of text can utilize interpolation, if we passed { name: 'tj', email: 'tj@vision-media.ca' } to the compiled function we can do the following:

#user #{name} <#{email}>

outputs <div id="user">tj &lt;tj@vision-media.ca&gt;</div>

示例用法:

mixin foo(item)
  p Foo called

mixin bar(item)
  p Bar called

mixin twoColumns(obj)
  .container-fluid
    .row(class=obj.class)
      for item in obj.items
        .col-xs-12.col-sm-3
          +#{item.template}(item)

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