How i can avoid same elements in jsrender?

*爱你&永不变心* 提交于 2019-12-13 21:04:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!