在 JsRender 中检查道具长度

Check for props length in JsRender

我想在迭代对象属性(如果有的话)之前显示一些文本。我尝试检查它的长度,但这不起作用。我该怎么做?

如下所示,tmpl1json1props 的正常循环,我需要的是 tmpl2json1,但是 value.datajson2

那个键总是被定义的,有时它有内容(json1),有时它是空的(json2

HTML

<script type="text/x-jsrender" id="tmpl1">
  {{props value.data}}
    <span>{{:key}}</span>
    <div>
    {{for prop}}
      <div>
        {{:#data.name}} - {{:#data.phone}}
      </div>
    {{/for}}
    </div>
  {{/props}}
</script>

<script type="text/x-jsrender" id="tmpl2">
{{if value.data.length}}
  <h1>This is the content:</h1>
  {{props value.data}}
    <span>{{:key}}</span>
    <div>
    {{for prop}}
      <div>
        {{:#data.name}} - {{:#data.phone}}
      </div>
    {{/for}}
    </div>
  {{/props}}   
{{/if}}
</script>

<div id="result1"></div>
<div id="result2"></div>

JS

var json1 = {
    "value": {
        "data": {
            "keyA": [
                {
                    "name": "foo",
                    "phone": 123
                }
            ],
            "keyB": [
                {
                    "name": "bar",
                    "phone": 456
                }
            ]
        }
    }
};

var json2 = {
    "value": {
        "data": []
    }
};


var tmpl1 = $.templates("#tmpl1");
$("#result1").html(tmpl1.render(json1));

var tmpl2 = $.templates("#tmpl2");
$("#result2").html(tmpl2.render(json1));

JSFIDDLE

一种方法是使用助手: http://www.jsviews.com/#helpers

{{if ~hasContent(value.data)}}
   <h1>This is the content:</h1>

function testForContent(data){
    for (var key in data) { 
        return true;
    };
    return false;
}

tmpl2.render(json1, {hasContent: testForContent}));

以鲍里斯为例,我将在此处留下一个 jQuery 实现和更新后的 fiddle

模板

{{if !~isEmptyObject(value.data)}}
  <h1>This is the content:</h1>
  {{props value.data}}
    <span>{{:key}}</span>
    <div>
    {{for prop}}
      <div>
        {{:#data.name}} - {{:#data.phone}}
      </div>
    {{/for}}
    </div>
  {{/props}}  
{{/if}}

帮手

$.views.helpers({
    isEmptyObject: function(obj)
    {
        return $.isEmptyObject(obj);
    }
});

JSFIDDLE