For with Index in Phoenix Templates

Looping through template variables

The standard way to iterate through lists in Phoenix templates is to use for/1

<%= for post <- @posts do %>
  <%= render "post.html", post: post %>
<% end %>

What index position am I in the loop?

Sometimes though you need to know the index of the item in the current loop. This might be useful for something like adding in a tabindex value.

To do this you need to use Enum.with_index/2, which returns the enumerable with each element wrapped in a tuple alongside its index.

Using something like the below you can now get the index value

<%= for {post, index} <- Enum.with_index(@posts) do %>
  <%= render "post.html", post: post, index: index %>
<% end) %>

John Polling

Developer, tinkerer, occasionally useful