Rails Views: creating a menu
I've run into kind of an odd issue. I'm showing a view where people can browse photos by different scopes, and I have the following menu in my view:
#photo_browser
= link_to 'Recent', browse_photos_path(:view=>'recent'), :class => 'button'
= link_to 'Best Photograhy', browse_photos_path(:view=>'best'), :class => 'button'
= link_to 'Most Loved Places', browse_photos_path(:view=>'loved'), :class => 'button'
= link_to 'Flagged', browse_photos_path(:view=>'flagged'), :class => 'button' if user_signed_in? && current_user.has_role?(:admin)
So, the currently selected view is a param in the url (ie.photos/browse?view=recent
).
Now, I'd like to add a "selected" class to whatever link is the current view. The problem is I haven't been able to think of a good way to do this. I could do something like...
- @presenter.view == recent? recentClass = 'selected' : recentClass = nil
= link_to 'Recent', browse_photos_path(:view=>'recent'), :class => 'button ' + recentClass
...for each link, but that seems really verbose and kind of sloppy.
So, my question is, is there a better way to handle this kind of situation?
Then, is it best for whatever code handles creating these menu开发者_运维知识库s to live in the view file, or in a helper, or in a Presenter model, or something else?
Thanks for the help!
I ended up solving this with a helper method:
def browse_menu_button(name,view)
@presenter.view == view ? btnClass = 'button selected' : btnClass = 'button'
link_to name, browse_photos_path(:view=>view), :class => btnClass
end
Then in my view:
#photo_browser
= browse_menu_button( 'Recent', :recent )
= browse_menu_button( 'Best Photography', :best )
= browse_menu_button( 'Most Loved Placed', :loved )
= browse_menu_button( 'Flagged', :flagged ) if user_signed_in? && current_user.has_role?(:admin)
That ended up working about as efficiently as anything else I could come up with.
精彩评论