I'm just getting used to Middleman and Ruby in general. What's the best way to generate a navigation with active states?
-
See Thomas's [magic_link_to](https://github.com/middleman/middleman/issues/303#issuecomment-4362124) helper for Middleman 3. `request.path` represents the current URL path. – sam Nov 30 '12 at 07:21
-
Stack overflow has become so sad that you can ask any question which has an answer in a manual, but you can't ask useful questions any more. Not a real question? I don't think that means what you think it means. – Binary Phile Apr 21 '14 at 15:15
2 Answers
In the current version of MM (2.x, though 3.0 is close), you can do it with the following additions to config.rb
and some tweaks in your nav file(s). Here is a working version in case I leave out some critical bits:
First create a helper function:
helpers do
def nav_active(page)
@page_id == page ? {:class => "Active"} : {}
end
end
Then, in the nav bar include file (in this case its a haml file) you can use the nav_active
helper as follows:
#HeaderNavigationBar
%ul
%li{nav_active("index")}= link_to t('top_navigation.home'), t('paths.index')
%li{nav_active("pricing")}= link_to t('top_navigation.pricing'), t('paths.pricing')
%li{nav_active("faq")}= link_to t('top_navigation.faq'), t('paths.faq')
The net result of this is to add the class "Active" to the link in the nav bar when the page is building built for this page. I.e. if the page is a file called "index" then the @page_id
will be "index" and that link will have the Active theme.
To complete the example, here is the excerpt from the scss style partial that defines active:
&.Active {
font-weight: bold;
}
In a later version of the header file, we actually removed the link when on the active page. It looks something like - which could clearly be tidied up, but FWIW :D:
%li{nav_active("index")}
-if "index" == @page_id
= t('top_navigation.home')
-else
= link_to t('top_navigation.home'), root()
... (etc)
Note that all the t('stuff') has to do with translation functions for i18n. You can ignore that. I didn't want to make the example syntactically wrong by trying to remove them.
Hope this helps - also see the forum at http://forum.middlemanapp.com/.

- 6,427
- 5
- 39
- 37
-
I do something like this if I know the page classes will stay the same :class => (page_classes === "index") ? "active" : "" – Ian Warner Apr 21 '13 at 14:33
Here’s a new gem for marking up a current link in Middleman with aria-current
(which you can then use to style off of): https://github.com/thoughtbot/middleman-aria_current

- 266
- 1
- 3