How can I change my application layout for certain views?

Is there any way to change / restrict the application layout for certain views? For example, I don’t want to render the header for a certain view…

When you’re in your view, Rails makes the current controller and action name available to you. So you could do something like this:

But, as I’ve said before, stuffing code in your views, especially conditionals, is a bad idea. It makes your view code harder to read and view code is already hard to read. And being easy to read is vitally important for real applications that last longer than a few weeks.

However, there’s an easy way around this.

Imagine you have a document viewing app; when viewing a list of documents, you want the header to be visible, when viewing an individual document, you don’t want the header. Easy.

In the index action, we grab our documents from somewhere and stick them in an instance variable (personally I wouldn’t do this, but that’s for another day). Rails then renders app/views/documents/index.html.erb for us, using the default layout – which is app/views/layouts/application.html.erb

In the show action, we grab an individual document from somewhere, stick it in an instance variable – but instead of letting Rails choose its defaults, we tell it what to render – use app/views/documents/show.html.erb, but using a different layout – app/views/layouts/no_header.html.erb

When defining these two layouts, we can use partials to share any common elements, so we’re not repeating ourselves. But the layouts themselves should be pretty simple to understand and we’re using the controller to make decisions about what gets rendered, which is exactly as it should be.

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe