2014-01-14 123 views
0

我有一個HTML模板,它應該根據控制器上的某些設置更改application.rb模板中的主體類。將控制器變量或參數傳遞給輔助模塊

我知道如何做到這一點,當我想從視圖中改變它。我這樣做是這樣的:

# in view 
<% layout_class("full", boxed: false) %> 

# helper method 
module TemplateHelper 
    def layout_class(class_name="") 
    content_tag("body", :id => "fluidGridSystem", :class => class_name) do 
     yield 
    end 
    end 
end 

忘記上面的行!

我想使控制器

# index_controller.rb 
class IndexController < ApplicationController 
    def index 
    @layout_class = "hello" 
    end 
end 

# app/helpers/template_helper.rb 
module TemplateHelper 

    def body_wrapper 
    content_tag("body", :id => "fluidGridSystem", :class => @layout_class) do 
     if some_logiC# show <body> only 
     yield 
     else # add some more <div>'s 
     blog_wrapper do 
      yield 
     end 
     end 
    end 

    def blog_wrapper(inner="", outer="") 
     content_tag("div", :class => outer) do 
     content_tag("div", :class => inner) do 
      yield 
     end 
     end 
    end 
    end 
end 

# application.rb 
<html> 
    <head> 
    </head> 
    <%= body_wrapper do %> # this part generates <body class="hello"> 
    <%= flash_messages %> 
    <%= yield %> 
    <% end %> # </body> 
</html> 

@layout_class不傳遞給助手裏這種情況發生。

  • 我該怎麼做?
  • 或者是視圖方法更好的解決?
  • 原因是我想添加breadcrumbs和依賴於控制器邏輯的body類。

回答

0

我認爲你的問題是你的助手方法的名稱是不同的,你打電話?

我不知道body_wrapper,但你打電話layout_class - 兩種不同的方法。你爲什麼不試試這個:

#app/helpers/template_helper.rb 
module TemplateHelper 
    def layout_class 
    content_tag("body", :id => "fluidGridSystem", :class => @layout_class) do 
    yield 
    end 
    end 
end 

#app/views/layouts/application.html.erb 
<body class="<%= layout_class(@layout_class) %>"> 

還有兩個潛在的方法來做到這一點:

1.更改佈局

如果你只有有一定的標準,以改變,你不妨試試:

#app/controllers/your_controller.rb 
layout :layout 

private 

def layout 
    if #your_logic 
     "layout" 
    else 
     "other_layout" 
    end 
end 

2.呼叫@layout_class直接從視圖

#app/views/layouts/application.rb 
<body class="<%= @layout_class %>"> 

這將顯示類,如果@layout_class設置,如果它不

+0

喜富不會公佈的「類」屬性,我已經更新了我的發佈更好的解釋,並添加了application.html.erb部分。請檢查一下。我也刪除了你指出的錯字。我希望現在更清楚。非常感謝提前 – Jan

+0

感謝您的更新 - 讓我看看! –