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 %>
  <div>
    # card markup without indexes
  </div>
<% 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 Enum.map function like so:

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

Postscript:

I built two products to help fund continued efforts for this website, it would mean a lot if you would check them out:
1. 2500+ Words for the Undermotivated Software Engineer - A short essay I wrote on the titled topic ($3).
2. Build 3 Chrome Extensions in Under 2 Hours - A course I built to teach chrome extension development ($9-20).