简体   繁体   English

在嵌入式 Elixir 中迭代列表

[英]Iterate over list in embedded Elixir

I am currently trying out embedded elixir (in my case .html.eex files).我目前正在尝试嵌入式长生不老药(在我的例子中是 .html.eex 文件)。 I know how to render elixir hashes, but I couldn't figure out how I create a content showing all items inside a list.我知道如何呈现 elixir 哈希,但我不知道如何创建显示列表中所有项目的内容。 In Ruby it would work like this:在 Ruby 中,它会像这样工作:

<% array.each do |item| %>
    <p> <%= item %> </p>
<% end %> 

The Elixir equivalent is Elixir 的等价物是

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

Note that you have to use a <%= in front of the for in Elixir.请注意,您必须在 Elixir 的for前面使用<%=

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.我很好奇这是否可以使用Enum模块,因为 Patrick Oscity 的答案依赖于Comprehensions ,它看起来只是Enum模块的包装器。

The answer is yes.答案是肯定的。 I first tried with Enum.each .我首先尝试使用Enum.each Which mysteriously only printed ok to the screen, but that's what Enum.each does;这神秘地只印ok屏幕,但是这就是Enum.each做; it always returns the :ok atom.它总是返回:ok原子。

I figuredEnum.map would be a better shot since it returns a list of results.我认为Enum.map会更好,因为它返回结果列表。 Take a look:看一看:

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

EEx works almost the same as ERB . EEx工作原理与ERB几乎相同。 In your ERB example you were passing a "block", which is analogous to a lambda or anonymous function, to the each function.在您的ERB示例中,您将一个类似于 lambda 或匿名函数的“块”传递给each函数。 In my EEx example the fn (item) -> takes the place of do |item|在我的EEx示例中, fn (item) ->代替了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.所以现在,您不仅可以迭代Lists ,还可以试验更多种类的函数,这些函数采用匿名函数来操作模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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