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:
<% if controller_name == 'documents' && action_name == 'show' %>
<%= render 'layouts/header' %>
<% end %>
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.
class DocumentsController < ApplicationController
@documents = ...
@document = ...
render action: 'show', layout: 'no_header'
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.