Search code examples
gruntjsyamlassemble

Change Partial in Assemble in Each


I just started using assemble and I currently have the following code:

default.hbs:

{{#each default.articles}}
    {{> layout  }}
{{/each}}

and default.yml:

articles:
  - article:
      title: Test 1
      image: image_path
      description: test 1
      reamore: link
      color: FFF
      layout: single

  - article:
      title: Test 2
      image: image_path
      description: test 2
      reamore: link
      color: 000
      layout: double

how can i use the layout in the yml data to define which partial to use?

so for example if the layout in yml is double it needs to load the double.hbs partial, and so forth. Is this at all possible? Or am i approaching this all wrong?

Any Help Would Be Awesome!


Solution

  • In Handlebars you can't dynamically choose a partial, but you can create a helper to do it:

    Handlebars.registerHelper('partial', function (key) {
      var partial = Handlebars.partials[key];
      if (partial) {
        var fn = Handlebars.compile(partial);
        var tmpl = fn(this);
        return new Handlebars.SafeString(tmpl);
      }
      throw new Error('Partial ' + key + ' is not registered with Handlebars');
    });
    

    Then use the helper:

    {{#each default.articles}}
        {{partial this.layout}}
    {{/each}}