我如何避免jsrender中的相同元素? [英] How i can avoid same elements in jsrender?

查看:71
本文介绍了我如何避免jsrender中的相同元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,请教{{for}}的jsrender数组

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"
    }
}]

和模板.

{{for address}}<b>{{>city}}</b>{{/for}}

呈现此模板将返回该数据

Rendering this template returns that data

Seattle
Sidney
Sidney

在使用{{for}}时,是否可以以某种方式避免重复相同的元素,即仅显示:

Can I somehow avoid a repeat of the same elements when using {{for}}, that is, to display only:

Seattle
Sidney

推荐答案

BTW而不是编写

{{for address}}<b>{{>city}}</b>{{/for}}

您可以通过编写来简化

<b>{{>address.city}}</b>.

消除重复项:

您当然可以在将数组传递给JsRender之前对其进行过滤.

You can of course filter your array before passing it to JsRender.

如果您不想这样做,可以使用一个助手来排除重复项,但是该助手需要查看数组中的前一项,而不是DOM,因为JsRender中的渲染是在之前进行的.插入DOM.

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.

这里是一个版本:

模板:

{{if !~alreadyInList(#index, address.city)}}
    <b>{{>address.city}}</b>
{{/if}}

JavaScript:

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

这篇关于我如何避免jsrender中的相同元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆