2011-07-14 24 views

回答

4

方法1:設置一個變量在該控制器

class SomeController 
    before_filter :set_to_use_menu 

    private 

    def set_to_use_menu 
    @use_menu = true 
    end 
end 

方法2:確定控制器在佈局中的名稱

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

@use_menu的用途是什麼,即它在哪裏使用? –

+0

謝謝我想我會使用第一種方法的修改版本。 – alste

+0

@michael:我相信PeterWong想要在佈局中使用@use_menu來調整菜單的渲染html – alste

4

如果我已經正確理解了需要在佈局中特別放置的問題。

使用<%=收率(:)%>在佈局所需的位置,例如:

# 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 %> 

其他位於 http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for

+2

謝謝,但這是控制器特定於操作,而不是控制器特定。我將不得不在控制器呈現的每個視圖中添加content_for – alste

1

除了content_for方法(可能或不可能是你想要的)之外,還有其他一些選項。

你可以使用的before_filter在你的控制器設置一個變量:

# 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 

或者,你可以獨自離開控制器,只是檢查控制器名稱在佈局:

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

只需在您的佈局中調用適當命名的部分

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

如果您的cont滾子是WidgetsController,那麼這將使用部分_widgets_menu.html.erb./app/views/layouts