我希望在迭代对象的属性之前显示一些文本(如果有的话)。我试着检查它的长度,但这不起作用。我怎么能这样做?
如下所示,tmpl1
json1
props
是tmpl2
的正常循环,我需要的是json1
value.data
,{ {1}}如json2
始终定义该密钥,有时它包含内容(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));
答案 0 :(得分:0)
一种方法是使用帮助器: 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}));
答案 1 :(得分:0)
以Boris为例,我将离开这里一个jQuery实现和更新的小提琴
TEMPLATE
{{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}}
HELPER
$.views.helpers({
isEmptyObject: function(obj)
{
return $.isEmptyObject(obj);
}
});