alste
alste

Reputation: 1455

Rails: Controller-specific menu in layout

How do I add a controller-specific menu (or div) inside a general application layout in Rails?

Upvotes: 4

Views: 2025

Answers (4)

Doug Johnston
Doug Johnston

Reputation: 854

Other than the content_for approach (which may or may not be what you want), there are a few additional options.

You could use a before_filter in your controller to set a 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 could leave the controller alone and just check for the controller name in your layout:

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

Upvotes: 1

edgerunner
edgerunner

Reputation: 14983

Just call an appropriately named partial in your layout

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

If your controller is WidgetsController, then this will use the partial _widgets_menu.html.erb under ./app/views/layouts

Upvotes: 1

PeterWong
PeterWong

Reputation: 16011

method 1: set a variable in that controller

class SomeController
  before_filter :set_to_use_menu

  private

  def set_to_use_menu
    @use_menu = true
  end
end

method 2: determine the controller's name in the layout

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

Upvotes: 4

warpc
warpc

Reputation: 221

If I have correctly understood the question you needs to special place in layout.

Use <%= yield(:) %> in desired position in 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 in http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for

Upvotes: 4

Related Questions