2
var data = {
   "name": "Jack",    
    "eventlist": {
        "1": {
           "title": "Title1"

    },
        "3": {
            "title": "Title2",

         }
    }
};

HTML

<div class="container">
<ul>
    <script id="list_template" type="text/x-handlebars-template">                                   
                <li>     

                </li>
            </script>   
        </ul>
</div>

I'm using handlebar js for templating.I wanted to know how can i iterate over data object and print the "title" and also the corresponding keys "1" , "3"

user1184100
  • 6,322
  • 27
  • 74
  • 116
  • 3
    **There is now built-in support for this**; see http://stackoverflow.com/q/11884960/50079 – Jon Jul 07 '13 at 22:05

1 Answers1

2

You could register a dedicated #each-like blockhelper which passes the keys of a hash/object-context with the "inner" context of the loop:

// based on the `#each` helper, requires jQuery (for jQuery.extend)
Handlebars.registerHelper('each_hash', function(context, options) {
    var fn = options.fn, inverse = options.inverse;
    var ret = "";

    if(typeof context === "object") {
        for(var key in context) {
            if(context.hasOwnProperty(key)) {
                // clone the context so it's not
                // modified by the template-engine when
                // setting "_key"
                var ctx = jQuery.extend(
                    {"_key":key},
                    context[key]);

                ret = ret + fn(ctx);
            }
        }
    } else {
        ret = inverse(this);
    }
    return ret;
});

Of course, the helper needs to be registered before you render the template.

Then in your template you can refer the the key with the _key-place holder:

<script id="list_template" type="text/x-handlebars-template">
     {{#each_hash eventlist}}
    <li>
        <span class="evl-key">{{_key}}</span> - 
            <span class="evl-title">{{title}}</span>
    </li>
    {{/each_hash}}
</script>

Then just render the template like any other handlebar template:

var source = $("#list_template").html();
var template = Handlebars.compile(source);

var html = template(data);

$("div.container ul").append(html);
vstm
  • 11,709
  • 1
  • 44
  • 45
  • The way you did the extend it does something pretty odd. I had to rewrite to ```javascript var ctx = jQuery.extend( {"_key":key}, {"_label":context[key]}); ret = ret + fn(ctx); ``` but I could totally be missing on something. – Dvid Silva Apr 03 '15 at 23:18