How to Enum get a index of a ecto member elixir phoenix

Viewed 150

I'm looking how to get a custom index of my ecto members in html show - generated from a resource mix phx.gen.html The goal is that every new post should have number. I have tried to create that function in PostsController, but I couldnt sort it out.

<%= for post <- @posts do %>

<%= post.title %>

<% end %>
2 Answers

Hello and welcome to Stack OverFlow :)

I'm pretty sure you are looking for:

<%= @posts |> Enum.with_index() |> Enum.map(fn({post, index}) ->  %>

  <%= index %>

  <%= post.title %>

<% end %>

In that way <%= index %> should point every ecto member and sort them.

Best Regards, ykostov

Variant with for:

<%= for {post, index} <- @posts |> Enum.with_index() do %>
<%= index %>
<%= post.title %>
<% end %>
Related