Iterate over list in embedded Elixir

I was curious if this were possible using the Enum module, since Patrick Oscity's answer relies Comprehensions which look to be just a wrapper for the Enum module.

The answer is yes. I first tried with Enum.each. Which mysteriously only printed ok to the screen, but that's what Enum.each does; it always returns the :ok atom.

I figured Enum.map would be a better shot since it returns a list of results. Take a look:

<%= Enum.map(@list, fn(item) -> %>
  <p><%= item %></p>
<% end) %>

EEx works almost the same as ERB. In your ERB example you were passing a "block", which is analogous to a lambda or anonymous function, to the each function. In my EEx example the fn (item) -> takes the place of do |item|.

So now, not only are you able to iterate over Lists, but you're able to experiment with a wider variety of functions that take an anonymous function that manipulates the template.


The Elixir equivalent is

<%= for item <- list do %>
  <p><%= item %></p>
<% end %>

Note that you have to use a <%= in front of the for in Elixir.

Tags:

List

Elixir