21

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?

Chris Glace
  • 215
  • 1
  • 2
  • 5

2 Answers2

42

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 %>
Sandro
  • 4,761
  • 1
  • 34
  • 41
3

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

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

jsFiddle example.

epidemian
  • 18,817
  • 3
  • 62
  • 71
  • @Puce it [seems to be necessary](https://github.com/sstephenson/eco#a-note-about-whitespace). Are you using a different Eco version? When removing the colon from the jsFiddle example linked on the answer an error is raised: `Error: Parse error on line 3: unexpected dedent`. – epidemian Jun 03 '15 at 14:50
  • Sorry you are right, I am not using the same template engine. – Puce Jun 04 '15 at 10:32