2

I'm using handlebar to create template for my backbone application and I'm using handlebar ifCond helper (source code already available). And using this helper function I can easily check between two values e.g

{{#ifCond val1 val2 operator="!="}}
{{/ifCond}}

Similarly I can use "==", ">", "<" operators.

But now I want to use &&, || operators within the if condition block, e.g.

{{#ifCond val1 && val2}}
{{/ifCond}}

As well as I want to use the mathematical operators within the if block, e.g

{{#ifCond val1+1 val2 operator=">"}}
{{/ifCond}}

Please suggest me what will be the best way to do this.

  • possible duplicate of [Logical operator in a handlebars.js {{#if}} conditional](http://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional) – Reactgular Jun 07 '14 at 19:41

1 Answers1

4

You can use the the "eval" method of Javascript to do this within you helper function.

HandleBars.registerHelper("evalExpression", function(){
        var me = this, result, 
        args = Array.prototype.slice.call(arguments),
        options =  args.pop(),
        params = args,
        expression = options.hash.expression;
        expression = expression.replace(/\#([0-9]+)/g, function(match, val){
            return params[val];
        });

        result = eval(expression);

        if(options.hash.returnBool == "true"){
            if(result){
                return options.fn(this)
            }else{
                return options.inverse(this);
            }
        }else{
            return result;
        }

    })

And then in the handlebar template use:-

{{#evalExpression val1 val2 expression="#0 && #1" returnBool="true"}}

{{else}}

{{/evalExpression }}

And:

{{#evalExpression val1 1 val2 expression="(#0+#1) > #2" returnBool="true"}}

{{else}}

{{/evalExpression }}
Indranil Mondal
  • 2,799
  • 3
  • 25
  • 40