rjoxford
rjoxford

Reputation: 361

Handlebars conditionals - boolean properties only?

Quick question. Is it possible to evaluate things other than a Boolean property in a handlebars conditional?

eg This works

//elsewhere...  myproperty = true
{{#if myproperty}}...

Any way other conditionals can be done? eg

//elsewhere...  myproperty = 3
{{#if myproperty<4}}...

Upvotes: 2

Views: 1334

Answers (3)

Sabin
Sabin

Reputation: 777

Best solution is to use ember-truth-helpers

So in your case you would use {{if (lt myproperty 4)}}

Upvotes: 0

user3886234
user3886234

Reputation:

Without a helper, you can't have if's evaluate conditions. You can, however, make a helper to do it:

Handlebars.registerHelper('iff', function(left, condi, right, options) {
    function ret(bool) {
        if (bool) {
            return options.fn(this);
        } else {
            return options.inverse(this);   
        }
    }

    switch (condi) {
        case "==":
            ret(left == right);
        case "!=":
            ret(left != right);
        case ">":
            //etc, etc, you get the idea
        default:
            return options.inverse(this);
    }
});

Usage:

{{#iff myproperty "<" 4}}
    Myproperty is less than 4
{{else}}
    Myproperty is greater than or equal to 4
{{/iff}}

--edit--

Haven't tried this yet but it looks sensible and straightforward. Begs the question why Handlebars doesn't support more complex conditionals natively...

It's good practice to separate your logic from your templates (views), because it makes your code more maintainable. Essentially, it's following the separation of concerns principle.

Personally, I think having a conditional if would be useful as well, because there is definitely a place for one-off if statements in templates while keeping your logic and view separate. However, by not including it by default, it somewhat saves users from themselves, so you don't end up seeing 20+ nested if statements.

Upvotes: 3

Kalman
Kalman

Reputation: 8121

You cannot do {{#if myproperty<4}} in the template.

See the following question for an example of what to do in such a case

How do I make a conditional helper with ember-cli and handlebars 2.0.0?

Upvotes: 1

Related Questions