【问题标题】:Render "0" value using a mustache template使用 mustache 模板渲染“0”值
【发布时间】:2012-11-15 17:29:15
【问题描述】:

我有一个属性值为“0”(零)的模型。我的模板看起来像这样:

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

如果myModel.count = 0,渲染的html什么都不是。这就像值“count”同时为空而不是空。

此案例的 Mustache 文档:https://github.com/janl/mustache.js#inverted-sections

【问题讨论】:

  • 你运行的是什么版本?我在 github 上发现了你的问题,据说它在 3 个月前的一次提交中得到了修复。 github.com/janl/mustache.js/pull/188 -> 见 hswolff 的评论。
  • 最新版本有帮助。现在它变成了否定的情况。但我仍然无法显示零。
  • 只是一种预感,但你可以试试{{{ count }}}{{& count}}
  • 它不会显示零,因为零是假的。让它显示的一种选择是将其设置为非假值(如字符串'0')。

标签: javascript templates web-applications mustache zero


【解决方案1】:

@bobthecow 在他的评论中回答了这个问题:

它不会显示零,因为零是假的。获得它的一种选择 显示是将其设置为非假值(如字符串'0')

【讨论】:

    【解决方案2】:

    一种方法是使用 lambda 来检查值。

    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;
        }
      }
    }
    

    希望对您有所帮助。

    【讨论】:

      【解决方案3】:

      不干净但有效

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-25
        • 1970-01-01
        • 1970-01-01
        • 2011-11-26
        • 2015-03-11
        • 1970-01-01
        • 1970-01-01
        • 2012-04-02
        相关资源
        最近更新 更多