在控制器中指定侧边栏的简单方法
我正在努力解决一些应该非常简单的事情 - 在控制器级别指定一个侧边栏。使用布局,您可以这样做:
layout 'admin'
所以我想对侧边栏执行相同的操作,如下所示:
sidebar 'search'
我知道我可以在视图中使用 content_for 指定侧边栏标记,但我宁愿在控制器上指定侧边栏水平,而不是在我的观点中重复代码(并弄乱)。我还希望能够在控制器之间共享侧边栏。
目前我已经在初始化程序中得到了这个(对于如此简单的事情来说,插件似乎有点矫枉过正):
module Sidebar
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def sidebar(partial)
# neither of these two work...
@sidebar = partial
instance_variable_set('@sidebar', partial)
end
end
end
ActionController::Base.send(:include, Sidebar)
然后在我的布局中我正在尝试
<%= render "shared/#{@sidebar}" %>
但无济于事......
有谁知道我做错了什么,或者我是否确实以正确的方式处理这件事?非常感谢任何帮助!
I'm wrestling with something that should be very simple - specify a sidebar at the controller level. With layouts you can do this:
layout 'admin'
so I'd like to do the same for a sidebar, with something like this:
sidebar 'search'
I know I could specify the sidebar markup with content_for in the views, but I'd rather specify the sidebar at the controller level and not repeat code in (and clutter up) my views. I'd also like to be able to share sidebars between controllers.
At the moment I've got this in an initializer (a plugin seems like overkill for something so simple):
module Sidebar
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def sidebar(partial)
# neither of these two work...
@sidebar = partial
instance_variable_set('@sidebar', partial)
end
end
end
ActionController::Base.send(:include, Sidebar)
and then in my layout I'm trying
<%= render "shared/#{@sidebar}" %>
but to no avail...
Does anyone know what I'm doing wrong, or if indeed I'm going about this the right way at all? Any help is greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个范围问题。该视图需要一个实例变量,但您的侧边栏方法在类范围内工作。
如果您的所有控制器都包含侧边栏,那么您可以考虑在应用程序控制器中定义一个实例变量。
另外,如果您没有其他方法,您可以进一步简化您的 mixin。
我个人不太喜欢这种方法。我更喜欢在视图文件中定义侧边栏的内容,并在未设置自定义值的情况下回退到标准值。
This is a scope issue. The view requires an instance variable but your sidebar method works in the class scope.
If all your controllers include a sidebar, then you can consider to define an instance variable in your application controller.
Also, if you don't have other methods, you can simplify your mixin even further.
Personally I don't like too much this approach. I prefer to define the content of a sidebar in the view file and fallback to a standard value in case no custom value is set.