2014-01-14 30 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

感谢您的更新 - 让我看看! –