Is there a ternary operator in handlebars.js?

后端 未结 4 1161
说谎
说谎 2021-01-07 19:15

In Handlebars, is there a ternary operator? I don\'t mean if else; I mean like a == true ? \"a\" : \"b\".

4条回答
  •  失恋的感觉
    2021-01-07 19:25

    I have a helper for this (pay attention that other helpers can also be used inside) https://gist.github.com/terion-name/d87ed8907f1bb2e25f32

    // app/helpers/iftrue.js
    import Ember from 'ember';
    
    export function iftrue(params) {
      if (params[0]) {
        return params.length === 2 ? params[0] : params[1];
      }
      if (params.length === 2) {
        return params[1];
      } else if (params.length === 3) {
        return params[2];
      }
      return null;
    }
    
    export default Ember.Helper.helper(iftrue);
    

    With two parameters: if first parameter evaluates to true it will be printed, otherwise second

    {{iftrue project.price 'N/A'}} // $9.99
    {{iftrue project.priceNotAvailable 'N/A'}} // N/A
    

    With three parameters: if first parameter evaluates to true second will be printed, otherwise third

    // If deadline is set formatted date will be printed, otherwise 'N/A'
    {{iftrue project.deadline (moment-format project.deadline 'DD.MM.YYYY') 'N/A'}} 
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题