I'm David Weirich, a software developer based out of Long Beach, CA. Hire me to work on your next project through my company Activated Apps LLC.

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

I'm David Weirich, a software developer based out of Long Beach, CA. Hire me to work on your next project through my company Activated Apps LLC.