Blaze: Logic (Not, Or, And…) in {{#if}} statement

情到浓时终转凉″ 提交于 2020-01-01 10:12:41

问题


Is there a way to do logic operation in {{#if}} statement? I was hoping for something like:

{{#if A && B}}
  some html
{{/if}}

I couldn’t find documentation about logic in blaze, so I guess it’s not supported. I just wanted to be sure. Sorry for the rather stupid question...


回答1:


As Billy Bob suggests, you would need parameterized helpers. Here are two global helpers you could use in any context:

Template.registerHelper('and',(a,b)=>{
  return a && b;
});
Template.registerHelper('or',(a,b)=>{
  return a || b;
});

Then you could use these with:

{{#if and a b}}
  a and b are both true-ish
{{/if}}
{{#if or a b}}
  a or b is true-ish
{{/if}}



回答2:


Spacebars is designed to avoid including logic operations in the html. But it does not mean you can't have one : you need to use helpers. Basically, you have 2 conditional cases:

  • The simple {{#if something}} and its twin {{#unless something}} (understand it as "if not"). This is what you want, and your helper would look like this

    Meteor.yourTemplate.helpers({
      something : function () {
         return A && B
      }
    });
    
  • The more complicated {{#if something 'value'}} where you use an argument for your something helper :

    Meteor.yourTemplate.helpers({
       something : function (value) {
          if (value === true){
            return true
          } else {
            return false
          }
      });
    



回答3:


here is my version :

Template.registerHelper("and", function() {
  return Array.prototype.slice.call(arguments, 0, -1).filter(arg => arg == true).length == arguments.length - 1;
});

Template.registerHelper("or", function() {
  return Array.prototype.slice.call(arguments, 0, -1).filter(arg => arg == true).length > 0;
});

You can now use x arguments to check, like :

{{#if and check_1 check_2 check3}}

You will notice the slice(0,-1), Blaze add one more argument to the function.



来源:https://stackoverflow.com/questions/36499595/blaze-logic-not-or-and-in-if-statement

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