Rails 3 - Dynamic Menu Item
I have an HTML menu in a partial and I 开发者_StackOverflow社区want to make the menu items dynamic (changing colors) depending on which page we are at. How can I do that?
Thanks
A common trick that is used to alter the appearance of menus to reflect the current page is to put a CSS selector or class that reflects the page name in the body tag.
Once you've done that, you can create different styles for each variation of page name that you want.
For example:
<!-- @page_name is 'home' in this example -->
<body class="<%= @page_name %>">
<!-- Lots of html here -->
<div class="nav_links">
<ul id="nav">
<li class="home"><a href="/"><span>Home</span></a></li>
<li class="about_us"><a href="/about"><span>About us</span></a></li>
<li class="store"><a href="/store"><span>Shop</span></a></li>
</ul>
</div>
Then the CSS can be anything you like, but something like:
body.home div.nav_links ul li.home { /* blah blah */ }
body.about_us div.nav_links ul li.about_us { /* blah blah */ }
This method ensures good separation of concerns: the visual styles (changing of your colors) stay in your stylesheets, and out of your code.
Create a helper to generate the html for the menu, and use the controller.controller_name
variable to change the class.
I had the same problem and I created to helper methods to set the active menu item.
def active_tab(id)
if id == menu_entry_id
'active'
else
'tab'
end
end
def menu_entry_id
if controller_path.match('/')
controller_path.gsub!('/', '_')
else
controller_path
end
end
Example menu
%li{:class => "#{active_tab 'admin_dashboard'}"}= link_to 'Dashboard', admin_dashboard_path
%li{:class => "#{active_tab 'admin_customers'}"}= link_to 'Customers', admin_customers_path
As you can see in the active_tab I pass the expected result from the controller_path (/ is replaced with _). The active_tab compares its input with the result of controller_path and returns active it both much or just tab.
I guess there might be other ways to do it, but I could not come up with something better.
精彩评论