Search code examples
htmlarrayshandlebars.jsassemble

How to generate a list of different handlebars partials?


I'm using handlebars.js with assemble.

I have a list of partials (which are svgs): icon-blue.hbs, icon-red.hbs, icon-white.hbs etc

I would like loop through an array and generate a different partial for each index.

I have the following in my JSON:

"list": [
 {
  "color": "red",
  "val": "Lorem ipsum"
 },
 {
  "color": "blue",
  "val": "Lorem ipsum"
 },
 {
  "color": "white",
  "val": "Lorem ipsum"
 }
]

then in index.hbs I want to do something like this:

{{#myData}}
  {{#each list}}
    {{> icon-{{color}} }} --> I know this isn't possible, so what can I do instead?
    <span>{{val}}</span>
  {{/each}}
{{/myData}}

Is there any way to do this? or any other way to achieve the expected result?


Solution

  • In handlebars you'll need to use a helper to join or concat variables.

    You can add a helper to assemble like this:

    app.helper('icon', function(name) {
      return 'icon-' + name;
    });
    

    Then you can use the built in partial helper and handlebars subexpressions:

    {{#myData}}
      {{#each list}}
        {{partial (icon color)}}
        <span>{{val}}</span>
      {{/each}}
    {{/myData}}