Control your layout
April 22nd, 2008
Recently, I added jQuery ajax tabs to an application. To reuse the existing views, I moved the relevant view code to partials for each required action:
render :partial => "entry", :object => journal_entry
and using something like the following in all the relevant controller methods:
format.html { render :partial => 'index' if request.xhr? }
As I added more features to the ajax tabs, I was conditionally rendering partials in every relevant action, as well as creating a partial. Not DRY.
layout provides a much DRY-er solution without the need for the partials. In application.rb:
layout proc { |controller| controller.request.xhr? ? false : 'application' }
When a controller action is invoked, if it is an XHR, no layout will be used. Otherwise the default Rails layout, ‘application’, will be used1.
1 layout expects the name of a layout to be returned from the proc; in this case, I am returning the name of the default. Returning false indicates that no layout should be used.
Leave a Reply