开发者

How to vary a helper called within a Rails 3 layout, depending on the controller

开发者 https://www.devze.com 2023-01-18 22:13 出处:网络
I\'m using the same layout for several controllers, and inside this layout I include a menu using a call to a helper, like this:

I'm using the same layout for several controllers, and inside this layout I include a menu using a call to a helper, like this:

<%= side_menu %>

What I'd like to do is vary the contents of side_menu depending on the controller that's invoking the layout. In an ideal world, I could define side_menu in application_controller.开发者_高级运维rb and in other helper files and then the appropriate helper would be selected depending on the controller; in other words, something like this:

# application_helper.rb
def side_menu
  "generic menu This goes here"
end

# users_helper.rb
def side_menu
  "menu for users goes here"
end

# guests_helper.rb
def side_menu
  "menu for guests goes here"
end

This doesn't work because in Rails 3 all helper files are loaded and I have no control over which side_menu will actually be called. It would be great if there were an option to load only application_helper.rb and the controller-specific helper, but there's not one (yet).

What's the best way to vary the content of a helper depending on the controller? I'm currently defining side_menu once in application_helper.rb and then checking to controller to see what to add. This feels wrong, since the problem nearly screams for a subclass-and-override answer -- which I can't do due to the "helper :all" behavior of Rails 3. Suggestions?


You can define this method in controller and add:

helper_method :side_menu

But maybe different solution would be better. I think that you can add _side_menu.html.erb in each controllers view folder and when you call <%= render :partial => 'side_menu' %> it should look for different files depending on current controller (however rememeber to add this file for all controllers).

Or you can mix these two methods. Add this helper method to controller and inside it render right file. This way it is better, because you get some default side menu and it won't crash when there is no side menu partial for a controller.

You can also in layout add <%= yield :side_menu %> and if you want to put something in side menu, just add <% content_for :side_menu do %> bla bla bla <% end %>.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号