Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access object keys in Handlebars templates?

I'm passing this into my template.

modules: {
  left: [],
  center: ['card', 'progressChart', 'tableOfChildren'],
  right: ['activity', 'details', 'triggers']
}

I want to do something like this... (psuedo code that I don’t think will work)

{{#each region in modules}}
  <div class="{{region}}">
  {{#each region}}
    <div class="{{this}} module"></div>
  {{/each}}
  </div>
{{/each}}
like image 775
Jesse Atkinson Avatar asked Feb 17 '15 20:02

Jesse Atkinson


People also ask

How do you iterate objects in Handlebars?

To iterate over an object with JavaScript and Handlebars. js, we can use the #each keyword. to add the Handlebars script and the template for looping through each entry in data . We use #each this to loop through each array property.

What is helper in Handlebars?

A Handlebars helper call is a simple identifier, followed by zero or more parameters (separated by a space). Each parameter is a Handlebars expression that is evaluated exactly the same way as described above in "Basic Usage": template {{firstname}} {{loud lastname}}

What is Handlebars template?

Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.


2 Answers

You can do

{{#each modules}}
  <div class="{{@key}}">
  {{#each this}}
    <div class="{{this}} module"></div>
  {{/each}}
  </div>
{{/each}}

Reference: http://handlebarsjs.com/builtin_helpers.html#iteration

like image 187
Gabriele Petrioli Avatar answered Sep 19 '22 04:09

Gabriele Petrioli


Probably duplicate, where Jon provides the best solution:

For arrays:

{{#each myArray}}
    Index: {{@index}} Value = {{this}}
{{/each}}

For objects:

{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}

Note that only properties passing the hasOwnProperty test will be enumerated.

like image 44
RegarBoy Avatar answered Sep 22 '22 04:09

RegarBoy