Full-Stack Developer

Elixir: Loop through maps in a Phoenix template

December 01, 2017

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 %>

David Weirich

Written by David Weirich who lives and works in Orange County, CA building useful things.