简体   繁体   中英

Nested model templating - backbone & underscore

I have got following 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

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

JavaScript

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

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

Working fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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