nit*_*moe 2 elixir phoenix-framework
我们以此模板位为例:
<%= if (length thread.posts) > 0 do %>
<%= for post <- thread.posts do %>
<%= for post <- thread.posts do %>
<%= render "post.html", post: post %>
<%= end %>
<% end %>
<%= end %>
Run Code Online (Sandbox Code Playgroud)
在各种框架中,您可以检查当前索引/迭代/如果在模板代码中循环收集时第一个(或最后一个),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 %>
Run Code Online (Sandbox Code Playgroud)
编辑
为了更符合您的原始代码......
<%= 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 %>
Run Code Online (Sandbox Code Playgroud)