Search code examples
ractivejs

Dynamically load partials in single Ractive instance


I would like to make a template that can determine which partial it will render, such that

In Template:

{{#objectA}}
  {{>partial}}
{{/}}
{{objectB}}
  {{>partial}}
{{/}}

Where partial is a property with template value on objectA and objectB

Is there any reasonable way of doing this, or something similar in a single instance?


Solution

  • Checkout Partial Expressions aka dynamic partials they do exactly that based on resolution of the partial name as a reference. Assuming each object had a foo property:

    {{#partial bar}}
     bar partial!
    {{/partial}}
    
    {{#partial qux}}
     qux partial!
    {{/partial}}
    
    {{#each items}}
        <li>item {{>foo}}
    {{/each}}
    

    And data was like:

    items: [
        { foo: 'bar' },
        { foo: 'qux' },     
    ]
    

    see http://jsfiddle.net/52k645wh/