简体   繁体   中英

Iterate over list in embedded 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 %> 

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.

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 figuredEnum.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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM