简体   繁体   English

嵌套模型模板 - 主干和下划线

[英]Nested model templating - backbone & underscore

I have got following JSON: 我有以下JSON:

var data = [
                {
                    "headline" : "This is headline",
                    "description": "This is description",
                    "icons": [
                        {
                            "url" : "http://farm9.staticflickr.com/8356/8404884161_f1d3efe9d6_b.jpg",
                        },
                        {

                            "url" : "http://farm9.staticflickr.com/8349/8167535290_d824c3e7d2_b.jpg"
                        }
                    ]
                }
            ];

and this template: 和这个模板:

<script type="text/template" id="items-tpl">
         <h1> <%= headline %> </h1>
         <p> <%= description %> </p>
         <ul>
             <li><%= url %></li>
         </ul>
 </script>

What is the best approach to render this in backbone using underscore (or any other method without additional libraries) 使用下划线(或没有其他库的任何其他方法)在骨干中呈现此内容的最佳方法是什么?

No need for backbone, unless you want to use it for more than your example. 不需要骨干,除非您想要使用它超过您的示例。 Do it like this with underscore. 用下划线做这个。

Template 模板

<script type="text/template" id="items-tpl">
         <h1> <%= headline %> </h1>
         <p> <%= description %> </p>
         <ul>
             <% for (var i=0; i < icons.length; i++) { %>
             <li><%= icons[i].url %></li>
             <% } %>
         </ul>
 </script>

Html HTML

<div id="renderedModel"></div>

JavaScript JavaScript的

var templateHtml = _.template($("#items-tpl").html(), data[0]);

$("#renderedModel").append(templateHtml);

Working fiddle here 在这里工作小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM