Hi,
Is it possible to create a row table counter inside a .eex template ? The example below shows only 0 ( expectation: 0 1 2 )
<table>
<tbody>
<% counter = 1 %>
<%= for _ <- ["list", "with", "data"] do %>
<tr>
<td><%= counter %></td>
</tr>
<% counter = counter + 1 %>
<% end %>
</tbody>
</table>
1 Like
You can use Enum.with_index
that will get you 0 1 2
<%= for {_,i} <- Enum.with_index(["list", "with", "data"]) do %>
<tr>
<td><%= i %></td>
</tr>
<% end %>
8 Likes
And the reason this is not doing what you expect is that this is making a ‘new’ binding with the name ‘counter’, which then vanishes when this loop ends so the next loop is bound to the original ‘counter’, which is always just 1. Remember that once you set a binding it is always set that and never changed, you can only make new bindings.
5 Likes