mikedidthis
mikedidthis

Reputation: 4897

Using a string as part of an #each loop in handlebars.js

Relatively new to handlebars.js, but not templating. I am using two loops to output markup in specific order. Both collections.intro and collections.elements are created by https://github.com/segmentio/metalsmith-collections.

Javascript

var order = ['intro', 'elements'];

collections.intro = [
 { title: 'One' },
 { title: 'Two' }
];

collections.elements = [
 { title: 'One' },
 { title: 'Two' }
];

Handlebars

{{#each order}}

  {{this}} /* intro, elements */

  {{#each ../collections.[this]}}
    {{this.title}}
  {{/each}}

{{/each}}

Is there anyway to use this from the order loop to access the correct collections. Both collections[intro] and collections[elements] work when hard coded.

Upvotes: 1

Views: 174

Answers (1)

mikedidthis
mikedidthis

Reputation: 4897

Managed to resolve this with a custom helper:

Javascript

Handlebars.registerHelper( 'collection', function ( slug, options ) {
  return options.data.root.collections[slug];
});

Handlebars

{{#each order}}

  {{#each (collection this)}}
    {{this.title}}
  {{/each}}

{{/each}}

Upvotes: 1

Related Questions