Creating New Conditionals in Handlebars

If you work with Handlebars long enough, you’ll start to notice a very annoying gap in its capabilities: conditionals. Now, Handlebars does come with a conditionals helper that simply tests whether or not the passed in value is truthy or not and acts accordingly. While this is fine for a good portion of scenarios, I guarantee there will come a time where you need a more robust solution. Today, we’re going to go over three conditional helpers that handlebars is lacking and how to make them yourself.

EqualTo

Handlebars.registerHelper('ifequal', function(value1, value2, options) {
    if(value1 === value2) {
        return options.fn(this);
    }
    return options.inverse(this);
});

LessThan and LessThanOrEqual

Handlebars.registerHelper('iflessthan', function(value1, value2, options) {
    if(value1 < value2) {
        return options.fn(this);
    }
    return options.inverse(this);
});
Handlebars.registerHelper('iflessthanorequal',
    function(value1, value2, options) {
        if(value1 <= value2) {
            return options.fn(this);
        }
        return options.inverse(this);
    }
);

If you need additional functionality (e.g., greater-than-or-eaual-to or not-equal-to), you can easily figure out what needs to be done given the examples provided. If you don’t feel like creating individual helpers for each kind of conditional, I found this really cool snippet on StackOverflow that may come in handy:

Handlebars.registerHelper('ifCond', 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);
        default:
            return options.inverse(this);
    }
});

You use it like this:

{#ifCond var1 '==' var2}}