Search code examples
if-statementhandlebars.js

how to use handlebars conditional helpers?


I have a Handlebars template with multiple iff blocks. iff is a custom helper for comparing values. The template compiles, but oo applying it i get no output and no errors.

Please what am I doing wrong?

iff helper

Handlebars.registerHelper("iff", function (v1, operator, v2, options) {
    switch (operator) {
        case '==':
            return (v1 == v2) ? options.fn(this) : options.inverse(this);
        case '===':
            return (v1 === v2) ? options.fn(this) : options.inverse(this);
        case '<':
            return (v1 < v2) ? options.fn(this) : options.inverse(this);
        case '<=':
            return (v1 <= v2) ? options.fn(this) : options.inverse(this);
        case '>':
            return (v1 > v2) ? options.fn(this) : options.inverse(this);
        case '>=':
            return (v1 >= v2) ? options.fn(this) : options.inverse(this);
        case '&&':
            return (v1 && v2) ? options.fn(this) : options.inverse(this);
        case '||':
            return (v1 || v2) ? options.fn(this) : options.inverse(this);
        case '!=':
            return (v1 != v2) ? options.fn(this) : options.inverse(this);
        case '!==':
            return (v1 !== v2) ? options.fn(this) : options.inverse(this);
        default:
            return options.inverse(this);
    }
});

template

{{#each message}}
    {{#iff type '==' -1}}
    <div class='sb-date'>{{text}}</div>
    {{/iff}}
    {{#iff type '==' 1}}
    <div class='sb sb-text sb-{{dir}}'>{{text}}<div class="sb-time">{{time}}</div></div>
    {{/iff}}
    {{#iff type '==' 5}}
    <div class='sb sb-text sb-{{dir}}'>{{text}}<div class="sb-time">{{time}}</div></div>
    {{/iff}}
    {{#iff type '==' 6}}
    <div class='sb sb-text sb-{{dir}}'>{{text}}<div class="sb-time">{{time}}</div></div>
    {{/iff}}
    {{#iff type '==' 2}}
    <div class='sb sb-image sb-{{dir}}'><img alt="" src="media/{{text}}" /><div class="sb-time">{{time}}</div></div>
    {{/iff}}
    {{#iff type '>' 2}}
    <div class='sb sb-file sb-{{dir}}'>media/{{text}}<div class="sb-time">{{time}}</div></div>
    {{/iff}}
{{/each}}

Solution

  • Found the solution.

    When passing an array use: {{#each this}}