All posts

Iterate a collection with indexes in Phoenix template

When I started looking into this I was already iterating over a collection with an Elixir comprehension like this:

<%= for card <- @cards do %>
    # card markup without indexes
<% end %>

I thought I might just be able to add an index to the comprehension but that’s not how comprehensions work.

Instead I needed to pipe the collection into the Enum.with_index function and then pipe the result of that into the function like so:

<%= @cards |> Enum.with_index |>{card, index}) ->  %>
    <div id="card" style="--color: <%= @settings["color"] %>; ; display: <%= if index == @card_index do "flex" else "none" end %>">
<% end) %>

The result of the map call the entire collection of generated markup, you can see where I use the index value to determine the display property for each card.

Resources I found useful when building this: