Underscore.js 模板解析_.each方法

<!-- 用于显示渲染后的标签 -->
<div  id="tplitem"></div>
<!-- 定义模板,将模板内容放到一个script标签中 -->
<script id="tpl" type="text/template">
<%_.each(datas, function(item) {%>
<ul class="listitem clearfix" >
<%_.each(item.cname, function(itemname) {%>
<li><a href="#"><img src="images/blank.gif" data-echo="<%=itemname.imagesurl%>" /><span><%=itemname.title%></span></a></li>
<%});%>
<%_.each(item.clist, function(itemlist) {%>
<li><a href="<%=itemlist.url%>/s?wd=<%=itemlist.title%>"><img src="images/blank.gif" data-echo="<%=itemlist.imagesurl%>" /><p><%=itemlist.title%></p></a></li>
<%});%>
</ul>
<%});%>
</script>
<script src="underscore-min.js"></script>
<script>
// 创建数据, 这些数据可能是你从服务器获取的  
var datas = [
{
"cname":[
{
"title": "肥料",
"url": "http://www.baidu.com",
"imagesurl":"images/p-0-0.jpg"
}
],
"clist":[
{
"id":"001",
"title": "复(混)合肥",
"url": "http://www.baidu.com",
"imagesurl":"images/p1.jpg"
},
{
"id":"002",
"title": "有机肥",
"url": "http://www.baidu.com",
"imagesurl":"images/p1.jpg"
},
{
"id":"003",
"title": "冲施肥",
"url": "http://www.baidu.com",
"imagesurl":"images/p1.jpg"
},
{
"id":"004",
"title": "叶面肥",
"url": "http://www.baidu.com",
"imagesurl":"images/p1.jpg"
},
{
"id":"004",
"title": "菌肥",
"url": "http://www.baidu.com",
"imagesurl":"images/p1.jpg"
},
{
"id":"006",
"title": "磷肥",
"url": "http://www.baidu.com",
"imagesurl":"images/p1.jpg"
}
]
},
{
"cname":[
{
"title": "种子",
"url": "http://www.baidu.com",
"imagesurl":"images/p-0-3.jpg"
}
],
"clist":[
{
"id":"007",
"title": "土豆",
"url": "http://www.baidu.com",
"imagesurl":"images/p1.jpg"
},
{
"id":"008",
"title": "小米",
"url": "http://www.baidu.com",
"imagesurl":"images/p1.jpg"
},
{
"id":"009",
"title": "大米",
"url": "http://www.baidu.com",
"imagesurl":"images/p1.jpg"
}
]
}
];
// 获取渲染元素和模板内容  
var element = $('#tplitem'),
tpl = $('#tpl').html();
// 解析模板, 返回解析后的内容  
var html = _.template(tpl, datas);
element.empty();
// 将解析后的内容填充到渲染元素  
element.html(html);
Echo.init({offset: 0,throttle: 0});
</script>

You may also like...

发表评论