如何检查 Handlebars 模板中的多个条件?

How can I check multiple conditions in a Handlebars template?

我有一个 handelbars 页面,根据 json 中的标题项目,它会显示不同的内容。

到目前为止,这是使用 helper if_wq

构建的

例如 if title = test 这有效

我想要一种方法来扩展此功能以显示 if title = testcolors.href = /test

所以条件只有在两个条件都为真时才有效。

我的代码示例

 {{#if_eq title 'test'}}
        True
    {{/if_eq}}

我的助手任务示例

handlebars.Handlebars.registerHelper('if_eq', function(a, b, opts) {
    if (a === b) {
        return opts.fn(this);
    } else {
        return opts.inverse(this);
    }
});

我的例子json

"range-list-page": {     
  "ranges": [            
    {                    
    "title": "test",  
  "colors": [                                               
    {                                                       
      "color": "#fff",                                      
      "label": "White",                                     
      "bordered": true,                                     
      "href" : "/test"      
    },                                                      
    {                                                       
      "color": "#F3DCAE",                                   
      "label": "Cream",                                     
      "href" : "http://google.com"                          
    },                                                      
    {                                                       
      "color": "#C5B7B0",                                   
      "label": "Cashmere",                                  
      "href" : "http://google.com"                          
    },                                                      
    {                                                       
      "color": "#D0B193",                                   
      "label": "Larch",                                     
      "href" : "http://google.com"                          
    }                                                       
  ]             

我定义了以下辅助方法:

(1) eq - 你已经有了,

Handlebars.registerHelper('eq', function(a, b) {
    if(a == b) // Or === depending on your needs
        return true;
    else
        return false;
}); 

(2) and - 请参阅下面的重要说明。

Handlebars.registerHelper('and', function () {
    // Get function args and remove last one (meta object); every(Boolean) checks AND
    return Array.prototype.slice.call(arguments, 0, arguments.length - 1).every(Boolean);
});

注意:如您所见,在执行 Array.prototype.slice.call 之前,我必须从 arguments 中删除最后一个参数,因为此处返回的最后一个参数是一个元对象。如果您不 trim 参数的最后结果,那么 every(Boolean) 将给出错误的结果。否则它只是一个 every(Boolean).

(3) 现在,假设我们有这两个助手,下面的示例可以检查 AND/EQ:

{{#if (and (eq var1 'STRING1') (eq var2 'STRING2') ) }}
...
{{/if}}