Custom sort_by in template/view

I have a category field on my model that I would like to sort in a custom order (e.g. I want all Other records to be listed last).

Right now I’m thinking about putting category in its own model and adding a field for sort_order to use when I query the database.

Is there an easy way to use Enum.sort_by/3 to do this? I also played around with using Enum.filter/2 to not match Other and then match Other, but I’m guessing there may be a simpler way.

Here is a simple example of what I’m trying to do:

<%= for video <- @videos do %>
  <%= video.category %>
  <%= video.url %>
<% end %>

I would like to output

History www.history.com
History www.ushistory.com
Sports www.sports.com
Other www.random.com

Thanks!

Axel

1 Like

@axelclark, I believe that what you want is some kind of helper in the view, that will generate the videos for you in the order that you want.

For example, let’s say that the template you showed me above is render by the `Rumbl.VideoView’ module. Inside of that module, I would use something like this:

defmodule Rumbl.VideoView do
  def ordered_videos(videos) do
    # code in here to order your videos by category. 
  end
end 

Then, because that view helper function will return an enumerable, we can use list comprehension just like you would with @videos.

<%= for video in <- (@videos |> ordered_videos) %>
...

Let me know if this works for you. Or if you find a more idiomatic solution. I’m always looking for the idiomatic way of writing code.

2 Likes