简体   繁体   中英

Nested loops in underscore templates with backbone

I'm using underscore for backbone templating, and I have a collection of models I'm passing to my underscore templates. I'm trying to loop through a series of objects in the collections' models, and then loop through an array of objects within each model. I tried doing this:

<% _.each(filters, function(filter,i){ %>
            <div class="filter <%= filter.get('title') %>" data-id="<%= i %>">
                <div class="filter-options-container">
                    <% var filterOptions = filter.get('filter'); for(var filterOption in filterOptions) { %>
                    <%= filterOption.id %>
                    <% } %>
                </div>
            </div>

            <% }); %>

But of course that's not right. I'm just not sure how to get a collection's model attribute, and then get that attribute's array. Here's my data structure:

在此处输入图片说明

Where that second filters array is the nested loop I'm trying to go through. Any idea how to write this out? Also tried nesting each statements:

<% _.each(filter.get('filter'), function(filterOption,i){ %>
  <%= i %>
<% }); %>

if i undestand you right, then:

you shouldn't sent to view backbone models as is, you should send them as toJSON().

for example:

_.template(tmpl_string)({filters : yourCollection.toJSON()});

template example:

<% _.each(filters, function(filter,i){ %>
    <div class="filter <%= filter.title %>" data-id="<%= i %>">
        <div class="filter-options-container">
            <%= _.pluck(filter.filters, 'id').join(', ') %>
        </div>
    </div>
<% }); %>

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