问题
Good day, have an array from lesson {{for}} for jsrender
[{
"name": "Pete",
"address": {
"city": "Seattle"
}
},
{
"name": "Heidi",
"address": {
"city": "Sidney"
}
},
{
"name": "Semen",
"address": {
"city": "Sidney"
}
}]
And template.
{{for address}}<b>{{>city}}</b>{{/for}}
Rendering this template returns that data
Seattle
Sidney
Sidney
Can I somehow avoid a repeat of the same elements when using {{for}}
, that is, to display only:
Seattle
Sidney
回答1:
I am not familiar with jsrender . But a quick search landed me into This Question & it's solution.
So, For this particular question you can do the same by just rewriting it to your requirement ,
{{for address}}
{{if ~domTextExists(text)}}
<b>{{>city}}</b>
{{/if}}
{{/for}}
And, For the helper ,
$.views.helpers({
domTextExists: function( text ) {
return $("#yourParentDIV:contains('"+text+"')").length;
}
});
View JsRender Helper for more detail.
回答2:
BTW instead of writing
{{for address}}<b>{{>city}}</b>{{/for}}
you can simplify by writing
<b>{{>address.city}}</b>
.
Eliminating duplicates:
You can of course filter your array before passing it to JsRender.
If you don't want to do that, you can use a helper to exclude duplicates, but the helper needs to look at the previous items in the array, not at the DOM, since the rendering in JsRender is happening prior to insertion into the DOM.
Here is one version:
Template:
{{if !~alreadyInList(#index, address.city)}}
<b>{{>address.city}}</b>
{{/if}}
Javascript:
var items = [...],
html = tmpl.render(items, {
alreadyInList: function(index, city) {
for (var i=0; i<index; i++) {
if (items[i].address.city === city) {
return true;
}
}
}
});
$("#result").html(html);
来源:https://stackoverflow.com/questions/28339082/how-i-can-avoid-same-elements-in-jsrender