Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 %> 
like image 956
Daniel Cukier Avatar asked Aug 24 '10 17:08

Daniel Cukier


People also ask

What is use of partials in Rails?

A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts. For example, you might have a login form that you want to display on 10 different pages on your site.

What is partial view in Rails?

Ruby on Rails Views Partials Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates. To create a partial, create a new file that begins with an underscore: _form.html.erb.


1 Answers

Currently, I'm using the following in my Rails 3/3.1 projects:

lookup_context.find_all('posts/_form').any? 

The advantage over other solutions I've seen is that this will look in all view paths instead of just your rails root. This is important to me as I have a lot of rails engines.

This also works in Rails 4.

like image 68
Rein Avatar answered Sep 28 '22 06:09

Rein