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

Viewed 1764

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.

2 Answers

@thread It works for me

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