gpt4 book ai didi

Elixir EEx : Determinig current iteration while looping through maps or collections

转载 作者:行者123 更新时间:2023-12-02 05:34:57 24 4
gpt4 key购买 nike

让我们以这个模板位为例:

<%= if (length thread.posts) > 0 do %>
<%= for post <- thread.posts do %>
<%= for post <- thread.posts do %>
<%= render "post.html", post: post %>
<%= end %>
<% end %>
<%= end %>

在各种框架中,您可以在循环模板代码中的集合时首先(或最后)检查当前索引/迭代/if,Elixir/Phoenix 是否提供任何类似的功能?举个例子,假设我们想要在第一次迭代中渲染一个特定的模板文件,然后为所有其他迭代渲染一个不同的模板文件,是否有实现此目的的最佳实践?

我考虑过设置一个变量来跟踪当前迭代,但 Erlang 中变量的不可变性质似乎并不能让这成为可能,甚至是可取的。

最佳答案

Enum.with_index 效果很好

<%= if (length thread.posts) > 0 do %>
<%= thread.posts |> Enun.with_index |> Enum.map(fn {post, inx} -> %>
<%= for post <- thread.posts do %>
<%= render "post.html", post: post %>
<%= end %>
<% end) %>
<%= end %>

编辑

为了更符合你原来的代码...

<%= if (length thread.posts) > 0 do %>
<%= for {post, inx} <- Enum.with_index(thread.posts) do %>
<%= for post <- thread.posts do %>
<%= render "post.html", post: post %>
<%= end %>
<% end %>
<%= end %>

关于 Elixir EEx : Determinig current iteration while looping through maps or collections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44012737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com