Handlebars.js无法读取属性' hash'未定义的

时间:2016-02-10 08:21:00

标签: javascript if-statement handlebars.js

这段代码:

<div id="banner-tree" class="hidden"></div>
    <script id="banner-template" type="x-handlebars-template">                  
        {{#each this}}
            {{#if this.text and this.outcomes}}
                <div class="banner-wrap" style="background-image: url({{imageSrc}});">
                    <div class="banner-desc">{{text}}</div>
                    <div class="banner-markets">Odds: {{outcomes.outcomeOdds}}</div>
                </div>
            {{else if this.outcomes}}
                <div class="banner-wrap" style="background-image: url({{imageSrc}});">
                    <div class="banner-markets">Odds: {{outcomes.outcomeOdds}}</div>
                </div>
            {{else if this.text}}
                <div class="banner-wrap" style="background-image: url({{imageSrc}});">
                    <div class="banner-desc">{{text}}</div>
                </div>                      
            {{else}}    
                <div class="banner-wrap" style="background-image: url({{imageSrc}});"></div>
            {{/if}}
        {{/each}}           
    </script>

这个脚本:

var templateBanner = $("#banner-template").html(); 
                var templateCompiled = Handlebars.compile(templateBanner);
                var compiledHtml = templateCompiled(response.data);
                var bannerTree = $('#banner-tree');
                bannerTree.html(compiledHtml);
                bannerTree.removeClass('hidden');

                Handlebars.registerHelper('if', function(conditional, options) {
                    if(conditional) {
                        return options.fn(this);
                    } else {
                        return options.reverse(this);
                    }
                });
                Handlebars.registerHelper('each', function(context, options) {
                    var ret = "";
                    for(var i=0, j=context.length; i<j; i++) {
                        ret = ret + options.fn(context[i]);
                    }
                    return ret;
                });

昨天没事。它按预期工作。今天早上我开始Cannot read property 'hash' of undefined。经过一些查询后,我发现故障位于{{#each this}}元素。或者我至少这么认为。当我更改上下文时,例如,data它不会产生任何结果(加载的JSON数组不会被推入div),但它也不会给我错误。当我删除整个ifology并留下

{{#each this}}
    <div class="banner-wrap" style="background-image: url({{imageSrc}});"></div>
{{/each}}

然后它部分工作。但不幸的是,我需要那些ifs。 所以,如果或每个人都会这样做。我在最近两个小时试图解决这个问题而且我空了:/

1 个答案:

答案 0 :(得分:2)

{{#if this.text and this.outcomes}}有错。重新定义整个语句后,只包含部分ifelse,它开始正常工作。