Search code examples
backbone.jshandlebars.js

Handlebar logical operations with helper function


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.


Solution

  • 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 }}