kannanrbk
kannanrbk

Reputation: 7134

Handlebars helpers inside loop

Template

   <script id='handlebar-template'>
    {{#each tags}}
            {{#isObject this}}
                <span>Object</span>
            {{else}}
                <span>String</span>
            {{/isObject}}
    {{/each}}
   </script>

Script

 <script>
    Handlebars.registerHelper('isObject', function(o) {
       return typeof o === "object";
    });

    var props = {"tags": ["Google"]}
    var html = $("#handlebar-template").html();
    var template = Handlebars.compile(html);
    console.log(template(props));
</script>

Output Expected

<span>String</span>

Actual Output

false

else block is executed but the output returns is false instead of <span>String</span>.

Upvotes: 2

Views: 610

Answers (1)

raidendev
raidendev

Reputation: 2799

You are using helper wrong or have a wrong helper.

In first case, change template to use {{#if}} helper:

{{#if (isObject this)}}
    <span>Object</span>
{{else}}
    <span>String</span>
{{/if}}

Look at this fiddle.

In second case, you need to implement {{else}} logic by yourself inside the helper.
Look at Handlebars block helpers documentation for conditionals.

Upvotes: 2

Related Questions