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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With