Rails conditional sidebar in application layout
layout, ruby-on-rails, view
Solution
You can check if a content for `:sidebar` exists and render the sidebar if true. Rails 2.3.5 will have a content_for? method. In the meantime, you can use my Helperful Gem.
- if has_content?(:sidebar)
.grid_8
= render :partial => 'shared/search'
= yield
.grid_4
= yield(:sidebar)
- else
.grid_12
= render :partial => 'shared/search'
= yield
Otherwise, you can assume if :sidebar == false then no sidebar.
def sidebar(enable = true, &block)
if enable
content_for :sidebar, &block
else
@fullpage = true
end
end
def fullpage?
!!@fullpage
end
- if fullpage?
.grid_12
= render :partial => 'shared/search'
= yield
- else
.grid_8
= render :partial => 'shared/search'
= yield
.grid_4
= yield(:sidebar)
Update:
If you are using Rails 3.x, check answer to a similar question for correct solution. The solution above doesn't work with Rails 3.
Problem
The following is my application layout file ``` .container_12.clearfix = render :partial => 'shared/flashes' .grid_8 = render :partial => 'shared/search' = yield .grid_4 = yield(:sidebar) ``` It has to grids, one for content and another for sidebar. Now I'm creating a login page in which I don't want to show my sidebar(just the single grid. I can simply create new layout with the .grid_12 div as the single grid. But this leaves me with 2 app layouts. How can I make the same application layout conditional to yield sidebar? If with sidebar, it would be same as above else just a single .grid_12 like the one below ``` .container_12.clearfix = render :partial => 'shared/flashes' .grid_12 = render :partial => 'shared/search' = yield ```