Search code examples
javascriptnode.jsnpmhandlebars.jsnode-modules

How to reference more than one element in an handlebars helper block on node.js?


So, I have an object like this:

object = {
 "group_1": [
  {
   "name": "Foo"
  }
 ],
 "group_2": [
  {
   "name": "Bar"
  }
 ]
}

And in my hbs view I'm doing like this:

{{#each group_1}}
 <p>{{name}}</p>
{{/each}}

{{#each group_2}}
 <p>{{name}}</p>
{{/each}}

Is there any way of concatenating both and not repeating code? The solution would be something like this:

{{#each group_1 + group_2}}
 <p>{{name}}</p>
{{/each}}

Any idea how to do this?


Solution

  • Handlebars itself does not support this. But you can still do:

    object.groups = object.group_1.concat(object.group_2);
    {{#each groups}}
    <p>{{name}}</p>
    {{/each}}

    Which seems to be a straightforward solution.

    Alternatively you can put both your groups into an object and iterate over it like this:

    let object = {
    	groups: {
    		'group_1': [
    			{
    				'name': 'Foo'
    			}
    		],
    		'group_2': [
    			{
    				'name': 'Bar'
    			}
    		]
    	}
    };
    {{#each groups}}
        {{!-- you can refference group name as @key here --}}
    	{{#each this}}
    		{{name}}
    	{{/each}}
    {{/each}}