I have a more succinct version of nav_link that works exactly like link_to, but is customized to output a wrapping li tag.
Put the following in your application_helper.rb
def nav_link(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
nav_link(capture(&block), options, html_options)
else
name = args[0]
options = args[1] || {}
html_options = args[2]
html_options = convert_options_to_data_attributes(options, html_options)
url = url_for(options)
class_name = current_page?(url) ? 'active' : nil
href = html_options['href']
tag_options = tag_options(html_options)
href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
"<li class=\"#{class_name}\"><a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a></li>".html_safe
end
end
If you look at the above code and compare it to the link_to code in url_helper.rb, the only difference is that it checks if the url is the current page, and adds the class "active" to a wrapping li tag. This is because I'm using the nav_link helper with Twitter Bootstrap's nav component which prefers links to be wrapped inside li tags and the "active" class applied to the outer li.
The nice thing about the above code is that it allows you to pass in a block into the function, just like you can do with link_to.
For example, a bootstrap nav list with icons would look like:
Slim:
ul.nav.nav-list
=nav_link root_path do
i.icon-home
| Home
=nav_link "#" do
i.icon-user
| Users
Output:
<ul class="nav nav-list">
<li class="active">
<a href="/">
<i class="icon-home"/>
Home
</a>
</li>
<li>
<a href="#">
<i class="icon-users"/>
Users
</a>
</li>
</ul>
In addition, just like the link_to helper, you can pass in HTML options into nav_link, which will be applied to the a tag.
An example of passing in a title for the anchor:
Slim:
ul.nav.nav-list
=nav_link root_path, title:"Home" do
i.icon-home
| Home
=nav_link "#", title:"Users" do
i.icon-user
| Users
Output:
<ul class="nav nav-list">
<li class="active">
<a href="/" title="Home">
<i class="icon-home"/>
Home
</a>
</li>
<li>
<a href="#" title="Users">
<i class="icon-users"/>
Users
</a>
</li>
</ul>