Elixir: Loop through maps in a Phoenix template

There are many examples online of looping through lists in a Phoenix template, but I came across an instance where I needed to loop over a map. I wanted the same clean for items <- items do syntax. After a bit of research, I found this for loop is actually considered a comprehension.

When looping through a map, you can simply create a tuple with two arguments {key, value}.

<% collection = %{"List" => ["Item", "Item", "Item"]} %>
<%= for {key, list} <- collection do %>
<%= key %> # List
<%= for item <- list do %>
<%= item %> # Item
<% end %>
<% end %>

2 thoughts on “Elixir: Loop through maps in a Phoenix template

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.