Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 287
nitomoe Avatar asked Feb 05 '23 10:02

nitomoe


1 Answers

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 %>
like image 156
Steve Pallen Avatar answered Jun 05 '23 15:06

Steve Pallen