Is there any Rails function to check if a partial exists?

Viewed 33610

When I render a partial which does not exists, I get an Exception. I'd like to check if a partial exists before rendering it and in case it doesn't exist, I'll render something else. I did the following code in my .erb file, but I think there should be a better way to do this:

    <% begin %>
      <%= render :partial => "#{dynamic_partial}" %>
    <% rescue ActionView::MissingTemplate %>
      Can't show this data!
    <% end %>
8 Answers

This works for me in Rails 6.1:

<% if lookup_context.exists?("override_partial", ['path/after/app/views'], true) %>
  <%= render partial: "path/after/app/views/override_partial" %>
<% else %>
  <%= render partial: "default_partial" %>
<% end %>

Here I have my partial nested some levels deeper than normal (app/views/path/after/app/views/_override_partial) so that's why I'm adding it as the prefixes array, but you can use lookup_context.prefixes instead if you don't need it.

I could have also used prepend_view_path on the controller. It's up to you :)

Related