Rails: controller-specific menu in layout

How to add a controller menu (or div) to a general application layout in Rails?

+4
source share
4 answers

method 1: set a variable in this controller

class SomeController before_filter :set_to_use_menu private def set_to_use_menu @use_menu = true end end 

method 2: determine the name of the controller in the layout

 <%- if controller_name == "your_controller_name" %> <%= render :partial => "the_menu" %> <%- end %> 
+4
source

If I understand correctly the question you need for a special place in the layout.

Use <% = yield (:)%> at the desired position in the layout, for example:

  # application.html.erb <%= yield(:right_menu) %> # show.html.erb <% content_for :right_menu do %> <!-- Everything in this block will be shown at the position yield(:right_menu) in layout --> <% end %> 

See more at http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for

+4
source

Besides the content_for approach (which may or may not be what you want), there are several additional options.

You can use before_filter in the controller to set the variable:

 # Controller class TestController < ApplicationController before_filter :set_variable def set_variable @my_variable = true end end # Layout if @my_variable # Do the controller-specific stuff you want to do end 

Or you can leave the controller alone and just check the name of the controller in your layout:

 # Layout if controller.controller_name == 'test' # Do the controller-specific stuff you want to do end 
+1
source

Just call your layout with the corresponding name indicated by the particle

 <%= render :partial => "#{controller_name}_menu" %> 

If your controller is a WidgetsController , then it will use partial _widgets_menu.html.erb in the ./app/views/layouts section

+1
source

All Articles