Let's take this template bit as an example:
<%= if (length thread.posts) > 0 do %>
<%= for post <- thread.posts do %>
<%= for post <- thread.posts do %>
<%= render "post.html", post: post %>
<%= end %>
<% end %>
<%= end %>
In various frameworks you're able to check the current index/iteration/if first (or last) while looping through collections in the template code, does Elixir/Phoenix provide any similar functionality? As an example, let's say we'd like to render a specific template file if we're in the first iteration and then render a different template file for all of the other iterations, is there a best practice for accomplishing this?
I've considered setting a variable to track the current iteration, but it doesn't seem like the immutable nature of variables in Erlang makes this possible or even desirable.
Enum.with_index works well
<%= 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 %>
EDIT
To be more in line with your original code...
<%= 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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With