Sparda
Sparda

Reputation: 610

Handlebars helper functions - extract property names

I have a JSON structure similar as below.

"markers": {
   "Lifestyle" : [
      {"Name1" : "Something"},
      {"Name2" : "Something"}
   ],  
   "Transport" : [
      {"Name1" : "Something"},
      {"Name2" : "Something"}
   ]

I want to create a menu with nested list-item using the above JSON.

<ul id="menu">
   <li class="Lifestyle">Lifestyle
      <ul class="sub-cat">
         <li>Something</li>
         <li>Something</li>
      </ul>
   </li>
   <li class="Transport">Transport
      <ul class="sub-cat">
         <li>Something</li>
         <li>Something</li>
      </ul>
   </li>
</ul>

I have tried adding a helper function to extract the name of the properties but i'm not sure how to add the sub-categories. Any advise is appreciated.

Edit: Added code

Handlebars.registerHelper('getCategory',function(object) {
                var categories = [];
                for(var x in object) {
                    categories.push(x);
                }
                console.log(categories);
                return categories;
            });

This just returns the category names. I know i can return HTML using the same helper but i'm not sure how i would add the nested structure.

Upvotes: 0

Views: 3253

Answers (2)

Jason
Jason

Reputation: 52527

You can use {{@key}} if you're going to be iterating.

Upvotes: 3

nikoshr
nikoshr

Reputation: 33364

In your case, the helper would be an iterator1 converting an object to a list of (key, value) pairs. NOte that an helper has to return HTML:

// context : object you wish to transform
// options.fn will contain the HTML block
Handlebars.registerHelper('pairs', function(context, options) {
    var cells = [], html, k;
    for (k in context) {
        if (context.hasOwnProperty(k)) {
            html = options.fn({
                key: k,
                value: context[k]
            }); 
            cells.push(html);
        }
    }
    return cells.join('');
});

And your template could look like this

<ul id="menu">
   {{#pairs .}}
   <li class="{{key}}">{{key}}
      <ul class="sub-cat">
      {{#each value}}
      {{#pairs .}}
          <li>{{key}}: {{value}}</li>
      {{/pairs}}
      {{/each}}
      </ul>
   </li>
    {{/pairs}}
</ul>

The nested level has to go through an each helper before being converted to a pair since the underlying data in an array.

Finally, a Fiddle http://jsfiddle.net/hnrQC/ to see this code in action.

1 See Block helpers in Handlebars: simple iterators

Upvotes: 2

Related Questions