在Handlebars中评估0

时间:2014-11-05 16:42:45

标签: templates handlebars.js conditional-statements

我正在使用周日为0的星期几。有些范围从星期一到星期日(日:1,最后:0),因此它应该显示范围而不是单日。但只能获得单日期。如何评估last == 0?

{{#if last}}
  <span>{{day day}} - {{day last}}</span>
{{else}}
  <span>{{day day}}</span>
{{/if}}

1 个答案:

答案 0 :(得分:1)

  

如何判断last == 0?

#unless帮助器会在虚假值(如0

)上返回true
//returns true if last is a falsy
{{#unless last}}
  <span>{{day day}} - {{day last}}</span>
{{else}}
  <span>{{day day}}</span>
{{/unless}}

因为它可以为null,你可以定义一个帮助器来测试一个特定的值,这里是我通常使用的时候我想在我的模板上面有一些逻辑或者虚假

&#13;
&#13;
var data = [
    {
    day: 1,
    last: null
    },
    {
    day: 2,
    last: 1
    },
    {
    day: 3,
    last: 0
    }

];

var source = $("#entry-template").html();


Handlebars.registerHelper('gte', function(target, condition, options) {
  if (target >= condition) {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});
var tempalte = Handlebars.compile(source);

$("body").append(tempalte(data));
&#13;
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="entry-template" type="text/x-handlebars-template">
{{!-- as suggested by @undeletable --}}
 {{#each this}}<span>{{day}}  {{#gte last 0}} - {{last}} {{/gte}} </span><br/>{{/each}}
</script>
&#13;
&#13;
&#13;