Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the loop index in an eco template

Is it possible to get the current loop index using the eco template engine?

For example in Jinja2 you can do

{% for var in array %}
    {{ loop.index0 }}
{% endfor %}

If not is there a more idiomatic way of getting at the index?

like image 428
Chris Glace Avatar asked May 17 '12 19:05

Chris Glace


2 Answers

From the CoffeeScript website:

# Fine five course dining.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses

Could also be written as

courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
for dish, i in courses
  menu i + 1, dish 

For the eco template, something like this should do it:

<% for val, idx in @varName: %>
<span>The index is <%= idx %> and value is <%= val %></span>
<% end %>
like image 78
Sandro Avatar answered Oct 23 '22 07:10

Sandro


Yes, just using the CoffeeScript for (but take care of the extra :):

<% for thing, i in @things: %>
  <%= i %>: <%= thing %>
<% end %>

jsFiddle example.

like image 41
epidemian Avatar answered Oct 23 '22 06:10

epidemian