当前位置: 首页 > 工具软件 > jsrender > 使用案例 >

jsrender在for循环中获取上级数据

华炜
2023-12-01

使用~root可以在模板中访问到顶层数据,从顶层数据往下就可以访问到所有数据了,如下:

<script id="item-list" type="text/x-jsrender">
    {{for items}}
        {{if ~root.type == "pic"}}
            <tr>
                <td>{{:id}}</td>
                <td><img src="{{:pic}}" /></td>
            </tr>
        {{else ~root.type == "name"}}
            <tr>
                <td>{{:id}}</td>
                <td>{{:name}}</td>
            </tr>
        {{/if}}
    {{/for}}
</script>
<script type="text/javascript">
    var picitems = [
        {id:1, pic:"/images/1.png" },
        {id:2, pic:"/images/2.png" },
        {id:3, pic:"/images/3.png" }
    ];
    var html = $("#item-list").render({ type: "pic", items: picitems });
    $("#allitems").append(html);

    var nameitems = [
        { id: 1, name: "/images/1.png" },
        { id: 2, name: "/images/2.png" },
        { id: 3, name: "/images/3.png" }
    ];
    var html = $("#item-list").render({ type: "name", items: nameitems });
    $("#allitems").append(html);

</script>

jsrender对语法要求非常严格,比如for,if前面不能有空格

参考:

http://www.cnblogs.com/tangmingjun/archive/2012/06/04/2534605.html

 类似资料: