【问题标题】:How to select a template conditionally with Ractive如何使用 Ractive 有条件地选择模板
【发布时间】:2023-04-09 18:36:01
【问题描述】:

我正在尝试有条件地选择一个模板。我的想法是我可以拥有一个包含组件列表的容器(视图),其中每个组件都会说明它应该使用哪个模板。

{{#view.components}}
   {{> {{template.id}} }}
{{/view.components}}

我希望部分声明从名为 id 的组件属性中解析 {{template.id}},然后解析部分。

view.components[0].template.id = "fooTemplate" (<script id="fooTemplate" />)
view.components[1].template.id = "barTemplate" (<script id="barTemplate" />)

并且积极地将#view.components 块解析为

{{>fooTemplate}}
{{>barTemplate}}

这个{{&gt;template.id}},告诉我它无法解析template.id。 这个{{&gt;{{template.id}} }} 告诉我它对t 一无所知。

我可以使用任何解决方法吗?

【问题讨论】:

    标签: ractivejs


    【解决方案1】:

    查看文档:http://docs.ractivejs.org/latest/partials in "Injecting partials"。

    你可以在部分中做这样的事情:

    ractive = new Ractive({
      el: myContainer,
      template: myTemplate,
      partials: {
        content: anyBooleanExpression ? fooTemplate: barTemplate,        
      }
    });
    

    您可以在模板属性中使用相同的条件:

    template: anyBooleanExpression ? fooTemplate: barTemplate,
    

    甚至使用更复杂的条件添加一个 swich 块或匿名函数。

    template: function(){ /* you complex logic */ },
    

    喜欢这个fiddle

    【讨论】:

      【解决方案2】:

      您可以如下定义您的模板:

         {{#view.components}}
            {{#FooTemp}}
              {{>fooTemplate}}
            {{/FooTemp}}
            {{#BarTemp}}
              {{>barTemplate}}
            {{/BarTemp}}
          {{/view.components}}
      

      你的模型是这样的:

      {
        view: {
          components: [
            {
              FooTemp: { ... }
            },
            {
              BarTemp: { ... }
            }
          ]
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-07
        • 2023-03-28
        • 2012-09-06
        • 2020-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多