Middleman - active class in subdirectory and children
I'm new to Middleman and for the life of me cannot dynamically set an active class for my navigation in a subdirectory and its children.
I have the following helper set and it works for a subdirectory (example: / about /) but it doesn't apply it to children (example: /about/otherpage.html)
module CustomHelpers
def nav_link_to(link, url, opts={})
if request.path == link
prefix = '<li class="active">'
else
prefix = '<li>'
end
prefix + link_to(link, url, opts) + "</li>"
end
end
Any help would be appreciated!
source to share
Problem solved!
After rooting in the reseller blogs, I discovered an ingenious solution from an EmberJS site publicly posted on GitHub.
To clarify, their assistant is:
def link_to_page name, url
path = request.path
current = path =~ Regexp.new('^' + url[1..-1] + '.*\.html')
if path == 'index.html' and name == 'about'
current = true
end
class_name = current ? ' class="active"' : ''
"<li#{class_name}><a href=\"#{url}\">#{name}</a></li>"
end
And then customize your template in the ul tag:
<%= link_to_page 'Projects', '/projects' %>
This also works for subdirectories and their children.
Hope it helps!
source to share
Here's an even shorter version:
in config.rb:
helpers do
def active_navigation(page)
current_page.url.include?(page) ? "active" : ''
end
end
and in your template, just define the path you want to check:
<ul>
<li class="<%= active_navigation("/projects") %>">
<%= link_to_page 'Projects', '/projects' %>
</li>
</ul>
Now, on any page where the url contains "/ projects", the li will have an "active" class.
So / projects, / projects / project1, / projects / list, etc. will cause the active class to be applied.
source to share