简体   繁体   中英

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

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

You need to edit your template to:

<ul class="test"> 
       {{#each people}}
            {{#ifThird @index}}
                <li>
                    {{firstName}}
                </li>
            {{else}}
                <li>
                    {{firstName}}{{lastName}}
                </li>
            {{/ifThird}}
       {{/each}}
   </ul>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM