Handlebars custom helper error: "options.fn is not a function"

时间:2016-02-12 19:38:57

标签: javascript jquery html handlebars.js

I'm pretty new to handlebars.js and I tried writing a simple if/else helper.

I used this codepen as a guideline.

I already found out that you shouldn't use the # in front of a custom helper but I can't figure out why i'm still getting this error.

This is my index.html :

<html>
<head>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js">
     </script>
     <script type="text/javascript" src="
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
    <script src="data.js"></script>
    <script src="helper.js"></script>
 </head>
<body>  
   <script id="entry-template" type="text/x-handlebars-template">
       <ul class="test"> 
           {{#each people}}
                {{ifThird @index}}
                    <li>
                        {{firstName}}
                    </li>
                {{else}}
                    <li>
                        {{firstName}}{{lastName}}
                    </li>
           {{/each}}
       </ul>
    </div>
  </div>
</script> 
</body>
</html>

... and this is data.js :

$(function(){
    var templateScript = $("#entry-template").html();
    var theTemplate = Handlebars.compile(templateScript);
    var context =   {
        people: [
            {firstName: "Yehuda", lastName: "Katz"},
            {firstName: "Carl", lastName: "Lerche"},
            {firstName: "Alan", lastName: "Johnson"},
            {firstName: "Dik", lastName:"Neok"},
            {firstName: "Bob", lastName:"van Dam"},
            {firstName: "Erik", lastName: "Leria"}
        ]
    };
    var html = theTemplate(context);
    $('.test').html(html);
    $(document.body).append(html);
})

... and this is helper.js (the error should be in here) :

Handlebars.registerHelper('ifThird', function (index, options) {
   if(index%3 == 0){
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

1 个答案:

答案 0 :(得分:4)

You need to edit your template to:

while True:
    time.sleep(1)
    if not mp.active_children():
        break

You need to start the block with {{#ifThird}} and close the block with {{/ifThird}}.