Logical Operator in a Handlebars.Js {{#If}} Conditional

Logical operator in a handlebars.js {{#if}} conditional

This is possible by 'cheating' with a block helper. This probably goes against the Ideology of the people who developed Handlebars.

Handlebars.registerHelper('ifCond', function(v1, v2, options) {
if(v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});

You can then call the helper in the template like this

{{#ifCond v1 v2}}
{{v1}} is equal to {{v2}}
{{else}}
{{v1}} is not equal to {{v2}}
{{/ifCond}}

Can't use logical operators in handlebars #if statement?

Turns out the #if helper can only test for properties to be true or false – not arbitrary expressions[source], so you have to do everything with helpers. Just write a function to compare things with logical operators and return true or false.

And to save you some trouble, the syntax for calling helpers doesn't use parentheses, either....arguments are space-separated like in rails. So it looks like:

{{myHelperFunction myarg1 myarg2}}

And if you want to nest helpers, you need parens:

{{myOuterHelper (myInnerHelper myarg1 myarg2)}}

Last tip from me, if you want to nest your helper with an #if, you need parens, too:

{{#if (myHelper myarg1 myarg2)}} content {{/if}}

Multiple OR operators in a handlebars.js {{#ifEquals}} conditional

First your helper ifEquals accepts only 2 arguments and your are passing much more than two arguments. Actually the || operator that you use is one argument and not an operator as you can think. Try chaining your tests if you need &&/and operator and if you need a ||/or operator try duplicating the blocks.

Second if you want to pass arguments you have to use '||' or '&&' otherwise it would lookup your data and || is not a field of your data.

Third another method would be to write a Helper that would accept much more arguments you'll find how to do this in the snippet below :

$(document).ready(function () {  var context = {    "regions" : [{"nominatorRegion":"BC Region"},{"nominatorRegion":"Saskatchewan Region"},{"nominatorRegion":"Alberta Region"},{"nominatorRegion":"Delaware Region"},{"nominatorRegion":"Michigan Region"}]  };  Handlebars.registerHelper('ifEqualsChained', function() {      var options = arguments[arguments.length-1];      // Assuming that all wanted operator are '||'      valueToTest=arguments[0];      for (var i = 1; i < (arguments.length - 1); i++) {        if (valueToTest === arguments[i]) {          return options.fn(this);        }      }      return options.inverse(this);  });  var source = $("#sourceTemplate").html();  var template = Handlebars.compile(source);  var html = template(context);  $("#resultPlaceholder").html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script id="sourceTemplate" type="text/x-handlebars-template"><ul>{{#each regions}}{{#ifEqualsChained nominatorRegion "BC Region" "Saskatchewan Region" "Alberta Region"}}<li>{{nominatorRegion}}</li>{{/ifEqualsChained}}{{/each}}</ul></script>
<div id="resultPlaceholder"></div>

Handlebarsjs check if a string is equal to a value

It seems you can't do it "directly"

Try use helper, why not?

Register helper in your javascript code:

Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});

Use in template:

{{#ifEquals sampleString "This is a string"}}
Your HTML here
{{/ifEquals}}

More details here:
Logical operator in a handlebars.js {{#if}} conditional

Update:
Another way:

lets assume, your data is:

var data = {
sampleString: 'This is a string'
};

Then (using jQuery):

$.extend(data, {isSampleString: function() {
return this.sampleString == 'This is a string';}
});

An use template:

{{#if isSampleString}}
Your HTML here
{{/if}}

Conditional "if statement" helper for Handlebars.js

I do see one minor syntax mistake which I believe could be the issue. If you are going to use a helper that takes a block, then you have to close it with the helper name. See how I've replaced your {{/if}} with {{/isApplyNow}}, like so:

    {{#isApplyNow}}
<a href="{{url}}" class ='active'>{{this.title}}</a>
{{else}}
<a href="{{url}}">{{this.title}}</a>
{{/isApplyNow}}

Handlebar logical operations with helper function

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


Related Topics



Leave a reply



Submit