Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nicest way to render different partials on a rails object?

I have a list of videos which i show in different ways. If I was only displaying it in one way, I would simply write

<% videos.each do |video| %>
<%= render video %>
<% end %>

This loads my _video.html.erb partial, but sometimes I'd like to load a different partial, depending on my view.

What's the most "Rails way" of having multiple views to render depending on the page it's being listed?

So on my home page I can render _video.html.erb, but on another page I could render _video_list.html.erb. Right now I'm just calling the method

<%= render 'videos/video_list' locals: video %>

But I get the feeling there's a nicer way? I feel like it would be great if I could write

<%= render video, 'list' %>

Any suggestions? Thanks

like image 215
David Sigley Avatar asked Sep 10 '25 13:09

David Sigley


1 Answers

To have the same model render different templates based on some condition, you can implement the to_partial_path method on any object and call render on that object:

def to_partial_path
  if list?
    "videos/list"
  else
    "videos"
  end
end
like image 130
shmargum Avatar answered Sep 13 '25 03:09

shmargum