简体   繁体   中英

Render "0" value using a mustache template

I have a model with a attribute with a value of "0" (zero). My template looks something like this:

    {{#count}}{{{count}}} items{{/count}}
    {{^count}}-{{/count}}

If myModel.count = 0 , the rendered html is nothing. It's like the value "count" is null and not null at the same time.

Mustache documentation for this case: https://github.com/janl/mustache.js#inverted-sections

@bobthecow answered it in his comment:

It won't display a zero because zero is falsey. One option to get it to display is to set it to a non-falsey value (like the string '0')

One method is to use a lambda to check the value.

http://jsfiddle.net/Bodman/yb83s/

var data = {

  "dataset" : [ 
    {count: 0},
    {count: -1},
    {count: 2},
    {count: false},
    {no_count:'yay'}
  ],


  "check_zero": function () {
    return function (text, render) {
      var result = '';
      var count = this.count;
      if(!isNaN(parseFloat(count)) && isFinite(count)){ 
          result = count;
      }else {
          result = render(text);
      }
      return result;
    }
  }
}

Hope that helps.

Not clean but works

{{#data.value}}
    {{data.value}}
{{/data.value}}
{{^data.value}}
    0
{{/data.value}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM