views:

34

answers:

2

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 %>
A: 

http://seanbehan.com/programming/render-partial-if-file-exists/

This seems to have a straightforward answer.

Elxx
A: 

I was struggling with this too. This is the method I ended up using:

<%= render :partial => "#{dynamic_partial}" rescue nil %>

Basically, if the partial doesn't exist, do nothing. Did you want to print something if the partial is missing, though?

Edit 1: Oh, I fail at reading comprehension. You did say that you wanted to render something else. In that case, how about this?

<%= render :partial => "#{dynamic_partial}" rescue render :partial => 'partial_that_actually_exists' %>

or

<%= render :partial => "#{dynamic_partial}" rescue "Can't show this data!" %>

Edit 2:

Alternative: Checking for existence of the partial file:

<%= render :partial => "#{dynamic_partial}" if File.exists?(Rails.root.join("app", "views", params[:controller], "_#{dynamic_partial}.html.erb")) %>
Jeff
My question is that I don't want to use Exceptions to do the flow control, which is a anti-pattern: http://stackoverflow.com/questions/1546514/java-exceptions-as-control-flow
Daniel Cukier
An exception is a type of flow control used to handle things that happen beyond a program's normal operation. If the dynamic partial is supposed to be there but something goes wrong and it ends up not being there, then that is a reasonable use for an exception (IMO, of course - proper use of exceptions is a holy war itself). I would say your alternative is to check the filesystem for whether or not the actual file exists. I'll update my answer with that code.
Jeff