最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jade Templates - Dynamically Calling a Mixin - Stack Overflow

programmeradmin1浏览0评论

How can I use a string from the json being fed into a Jade template to dynamically load a mixin? Below, the goal is for twoColumn.jade to load the foo and bar mixins.

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"     
            }
        ]            
    }
}

How can I use a string from the json being fed into a Jade template to dynamically load a mixin? Below, the goal is for twoColumn.jade to load the foo and bar mixins.

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"     
            }
        ]            
    }
}
Share Improve this question asked Jun 24, 2014 at 16:43 Walter RomanWalter Roman 4,7892 gold badges33 silver badges37 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

This is a feature that is not very obvious in Jade, as it is not explicitly mentioned in the documentation. You can actually use the interpolation syntax (#{...}) for dynamically choosing the mixin name.

From the Jade language guide:

interpolation? yup! both types of text can utilize interpolation, if we passed { name: 'tj', email: '[email protected]' } to the piled function we can do the following:

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

outputs <div id="user">tj &lt;[email protected]&gt;</div>

Example usage:

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)
发布评论

评论列表(0)

  1. 暂无评论