Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over list in embedded Elixir

Tags:

list

elixir

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 %> 
like image 412
Stoecki Avatar asked Feb 11 '15 16:02

Stoecki


2 Answers

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.

like image 51
Patrick Oscity Avatar answered Nov 15 '22 02:11

Patrick Oscity


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.

like image 12
Breedly Avatar answered Nov 15 '22 01:11

Breedly