Getting key's in handlebar

蓝咒 提交于 2019-12-11 03:47:32

问题


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"


回答1:


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);


来源:https://stackoverflow.com/questions/12032851/getting-keys-in-handlebar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!