How to compare a value in handlebars?

情到浓时终转凉″ 提交于 2020-03-22 09:47:20

问题


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

回答1:


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



回答2:


This is Sunil More's answer just with <, >= and <= added.

 Handlebars.registerHelper("when", (operand_1, operator, operand_2, options) => {
    let operators = {                     //  {{#when <operand1> 'eq' <operand2>}}
      'eq': (l,r) => l == r,              //  {{/when}}
      'noteq': (l,r) => l != r,
      'gt': (l,r) => (+l) > (+r),                        // {{#when var1 'eq' var2}}
      'gteq': (l,r) => ((+l) > (+r)) || (l == r),        //               eq
      'lt': (l,r) => (+l) < (+r),                        // {{else when var1 'gt' var2}}
      'lteq': (l,r) => ((+l) < (+r)) || (l == r),        //               gt
      'or': (l,r) => l || r,                             // {{else}}
      'and': (l,r) => l && r,                            //               lt
      '%': (l,r) => (l % r) === 0                        // {{/when}}
    }
    let result = operators[operator](operand_1,operand_2);
    if(result) return options.fn(this); 
    return options.inverse(this);       
  });


来源:https://stackoverflow.com/questions/33316562/how-to-compare-a-value-in-handlebars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!