boolean logic within a handlebars template

一笑奈何 提交于 2019-12-05 10:27:59

You can't do it directly but it isn't that hard to do with a little bit of arguments parsing and a variadic helper. Something like this:

Handlebars.registerHelper('if_all', function() {
    var args = [].slice.apply(arguments);
    var opts = args.pop();

    var fn = opts.fn;
    for(var i = 0; i < args.length; ++i) {
        if(args[i])
            continue;
        fn = opts.inverse;
        break;
    }
    return fn(this);
});

And then in a template you can say:

{{#if_all a b c}}
    yes
{{else}}
    no
{{/if_all}}

You can use as many arguments to {{#if_all}} as you need. You might want to adjust the truthiness test to match Handlebars since {{#if}} treats

`false`, `undefined`, `null`, `""` or `[]` (a "falsy" value)

as falsey and everything else as truthy whereas [] is truthy in JavaScript.

Demo: http://jsfiddle.net/ambiguous/vrb2h/

may be you can try this handlebars helper:

Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {

switch (operator) {
    case '==':
        return (v1 == v2) ? options.fn(this) : options.inverse(this);
    case '===':
        return (v1 === v2) ? options.fn(this) : options.inverse(this);
    case '<':
        return (v1 < v2) ? options.fn(this) : options.inverse(this);
    case '<=':
        return (v1 <= v2) ? options.fn(this) : options.inverse(this);
    case '>':
        return (v1 > v2) ? options.fn(this) : options.inverse(this);
    case '>=':
        return (v1 >= v2) ? options.fn(this) : options.inverse(this);
    case '&&':
        return (v1 && v2) ? options.fn(this) : options.inverse(this);
    case '||':
        return (v1 || v2) ? options.fn(this) : options.inverse(this);
    default:
        return options.inverse(this);
}

});

and invoke it like this :

 {{#ifCond showDistance "&&" distance}}
      <span class="distance">
          {{distance}}
      </span>
 {{else}}
      {{#if showRegion}}
           <span class="region">
           </span>
      {{/if}}
 {{/ifCond}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!