使用~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>
参考:
http://www.cnblogs.com/tangmingjun/archive/2012/06/04/2534605.html