Rendering a Partial as an Alternative

Suppose that I want to have a block of default content within a template that is replaced with the content of a specific partial only if that partial exists. Obviously there is the brute force approach of simply rendering the default content unless the relevant partial file exists in which case the relevant partial is rendered instead. I suspect that there may be a more elegant way to skin this cat. Any suggestions?

Thanks for any input.

          ... doug

Doug,

This may actually be worse but it is another way…

<% begin %>

<%= render :partial => ‘custom’ %>

<% rescue ActionView::MissingTemplate %>

Default

<% end %>

Anthony Crumley

http://commonthread.com

Hi Anthony,

<% begin %>   <%= render :partial => 'custom' %> <% rescue ActionView::MissingTemplate %>   Default <% end %>

why this begin and end are used what is mean by <% rescue ActionView::MissingTemplate %>

can you tell me

Rahul,

Exceptions handling in Ruby is done the following way.

begin

rescue

end

When a partial template is missing Rails will throw an exception. As a result, to catch a missing partial template exception (ActionView::MissingTemplate) you need to rescue that exception by name. In ERB the syntax for this is <% rescue ActionView::MissingTemplate %>.

Anthony Crumley

http://commonthread.com

This may actually be worse but it is another way...

In terms of elegance, I think that it's about a toss up. However, I think that your suggestion has a slight distinct advantage. If I use my approach, I have to deal with the actual partial twice, once to test whether it exists and once to render it if it does. Using your approach, I only have to deal with the actual partial once, i.e., to render it. I'm adopting your approach whch, btw, works great. Thanks for the suggestion.

        ... doug

Hi Anthony ,

Thanks for reply, its good to know that exception handling in rails is done like this.

thanks

Rahul