Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a value in handlebars?

I want display different HTML depending on a condition.

It doesn't seem to compare those two values and it always shows the first variant. How can I compare the predefined values to the original value from JSON so that it can execute properly?

{{#each this}}
  {{#each visits}}
    <div class="row">
      {{#if variable_from_json }}
        <div class="col-lg-2 col-md-2 col-sm-2">
          <i class="fa fa-home"></i>
         </div>
      {{else}}
        <div class="col-lg-2 col-md-2 col-sm-2">
          <i class="fa fa-plus symbol-hospital"></i>
        </div>
      {{/if}}
    </div>
  {{/each}}
{{/each}}

JS code

Handlebars.registerHelper('if', function (variable_from_json, options) {
    if (variable_from_json === "M") {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});
like image 358
xxCodexx Avatar asked Dec 18 '22 22:12

xxCodexx


1 Answers

To compare values like ==,>=,|| ,&& Create one helper which will handle all cases

Handlebars.registerHelper( "when",function(operand_1, operator, operand_2, options) {
  var operators = {
   'eq': function(l,r) { return l == r; },
   'noteq': function(l,r) { return l != r; },
   'gt': function(l,r) { return Number(l) > Number(r); },
   'or': function(l,r) { return l || r; },
   'and': function(l,r) { return l && r; },
   '%': function(l,r) { return (l % r) === 0; }
  }
  , result = operators[operator](operand_1,operand_2);

  if (result) return options.fn(this);
  else  return options.inverse(this);
});

Use this operator in handlebar file For eg. == operator

 {{#when <operand1> 'eq' <operand2>}}
   // do something here
 {{/when}}
like image 124
Sunil More Avatar answered Jan 03 '23 10:01

Sunil More