Reputation: 597
I am currently trying out embedded elixir (in my case .html.eex files). I know how to render elixir hashes, but I couldn't figure out how I create a content showing all items inside a list. In Ruby it would work like this:
<% array.each do |item| %>
<p> <%= item %> </p>
<% end %>
Upvotes: 23
Views: 11714
Reputation: 14326
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.
Upvotes: 14
Reputation: 54734
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.
Upvotes: 43