Search code examples
javascriptjqueryhandlebars.js

handlebars list all values into each


Using handlebars.js want to list all values from a key for each parent key, in my case tabs

JSON:

{
  "Default":{
    "tabs": [{
      "name":"About",
      "tag":"[[ABOUT]]"
    },{
      "name":"Contact",
      "tag":"[[CONTACT]]"
    }]
  }
}

TEMPLATE:

{{#tabs}}
<div class="box">
  <input id="tab{{@index}}" type="radio" name="tabs" {{#if @first}}checked{{/if}} />
  <div class="tabNames">
    {{#each name}}
    <label for="tab{{@index}}">{{@name}}<i></i></label>
    {{/each}}
  </div>
  <section id="content{{@index}}">{{tag}}</section>
</div>
{{/tabs}}

I need this output:

<div class="box">
    <input id="tab1" type="radio" name="tabs" checked />
    <div class="tabNames">
        <label for="tab1">About</label>
        <label for="tab2">Contact</label>
    </div>
    <section id="content1">[[ABOUT]]</section>
</div>
<div class="box">
    <input id="tab2" type="radio" name="tabs" />
    <div class="tabNames">
        <label for="tab1">About</label>
        <label for="tab2">Contact</label>
    </div>
    <section id="content2">[[CONTACT]]</section>
</div>

The problem is on #each name.

Right now is returning only 1 x label and I need all of them.

Any help please?


Solution

  • You can't call #each over a non-collection value like name (string). #each is for iterating over an array or the properties of an object. You do not have a collection of names to iterate over. You have an array of "tab" objects, each with a "name" property. Since you are already in the context of an element of the tabs array where you want to list all tab names, you will need to use a Handlebars path to get the tabs array from the parent context:

    {{#each ../tabs}}
        <label for="tab{{@index}}">{{name}}<i></i></label>
    {{/each}}
    

    Note that you do not access a property like {{@name}}, but, rather, like {{name}}.

    Also, in your example, all of your index start at 1 (tab1, tab2). Arrays are 0-indexed, so you should expect your output to be 0-indexed as well: tab0, tab1, etc.