jashkenas / underscore

JavaScript's utility _ belt
https://underscorejs.org
MIT License
27.33k stars 5.53k forks source link

How do you display total number of records in a template? #2811

Closed lschneiderman closed 4 years ago

lschneiderman commented 5 years ago

I'm having trouble getting any answers on underscore.js on stackoverflow, so I'm just going to ask here. How do you display the total number of records in a template? In this example, how would I display totalNum?

spattanaik75 commented 5 years ago

shouldn't it be

_.each(items,function(item,key,items) { %> <%- items.length %> of addresses in this search <% });

jgonggrijp commented 4 years ago

For future reference, if your items looks like this:

[{id: 100}, {id: 101}]

Then you can render something for each item and then display the total number of them at the end like this:

<% _.each(items, function(item, index, list) { %>
    <!-- print whatever you want about each `item` here -->
<% }); %>
Total number of items: <%= items.length %>

If you want to tally during iteration to show something like “item 5 of 10”, this will work:

<% _.each(items, function(item, index, list) { %>
    This is item <%= index %> of <%= list.length %>.
<% }); %>

@lschneiderman @spattanaik75