Search code examples
htmljsonbackbone.jshandlebars.js

How do I iterate through a JSON structure with Handlebars


I'm trying to build a menu from some JSON using handlebars expressions. I need help figuring out how to iterate through the json to access the data values.

Here's what I have now:

<ul>Pseudo HTML Code for Menu 
    {{#each}}
        <li>
            {{menuGroup.parentMenuName}}
            <ul><li>menuItems.subMenuName</li></ul>
        </li>
    {{/each}}
</ul>

{  Pseudo JSON
   "menu":[  
      {  I have 6 of these arrays and I want to get the Parent menu name and description placed into each li tag
         "menuGroup":{  
            "parentMenuName":"MAIN",
            "description":"myDesc",
            "displayOrder":1,
            "menuCategory":"myCat",
         },
         "menuItems":[  
            {  
               "subMenuName":"Payments",
               "shortCode":"PAY"
               "key":"primaryKey"
            },
         ]
      }
   ]
}

Ultimately, for each {Object} within "menu", I would have an "li" tag filled with data from the nested objects. Any help would be greatly appreciated. I'm not super familiar with handlebar expressions.

Update:

In other words, I have a structure like this {{menu.[0].menuGroup.parentMenu}}. I can get the value this way perfectly. For one item. How do I loop through to get the value from all 6 arrays. Not just [0] (the first)


Solution

  • You have defined the menuItems as an array of Objects that is why your code is not working.

    "menuItems":[  
            {  
               "subMenuName":"Payments",
               "shortCode":"PAY"
               "key":"primaryKey"
            },
         ]
    

    Either change this to

    "menuItems": {  
        "subMenuName":"Payments",
        "shortCode":"PAY"
        "key":"primaryKey"
    }
    

    Or write the template as

    <li>
        {{#menuItems}}
            {{subMenuName}}
        {{/menuItems}}
    </li>
    

    And your code should work.

    Working example can be found here. http://jsfiddle.net/prabhat_rai/mhb1supn/