[英]Conditional template based on data in underscore.js
我正在使用underscore.js html模板來呈現以下json(簡體)的html:
[
{
"$id": "1",
"Type": 3000,
"Date": "2014-02-26T07:17:03+05:00"
},
{
"$id": "1",
"Type": 2000,
"Date": "2014-02-26T07:17:03+05:00"
},
]
我必須根據“ Type
字段為數組中的每個項目渲染HTML。 每種Type
的html都有很大的不同,我當前的模板到處都是html,如果有其他條件,則非常像這樣:
<script type="text/template" class="template">
<% _.each(streams, function(data) { if(data.Type == 3000){ %>
// Some long html here for type 3000
<% if(data.Type == 2000){%>
// html for type 2000
<% }}}); %>
</script>
如何避免在模板中寫其他條件,並可能為每個“類型”創建一個模板,以便輕松維護模板。
可以通過調用模板內部的模板來完成,例如:
<script type="text/template" class="template">
<div>
<% _.each(data, function(child) { %>
<%= _.template($('.template_'+child.Type).html())(child) %>
<% }); %>
</div>
</script>
<script type="text/template" class="template_3000">
<div>
3000 Template
</div>
</script>
<script type="text/template" class="template_2000">
<div>
2000 Template
</div>
</script>
有關工作示例,請參見http://jsfiddle.net/L2b9H/ 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.