A simple gem to implement active states on links using the standard Rails link_to helper.
This can be helpful in navigation lists or buttons to give them a class when the current URL matches a condition on the link helper.
Add this line to your application's Gemfile:
gem 'link_to_active_state'
Or install from the repository:
gem 'link_to_active_state', git: 'git://github.com/robotmay/link_to_active_state.git', tag: 'v1.0.5'
And then execute:
$ bundle
Or install it yourself as:
$ gem install link_to_active_state
This gem adds a small bit of extra functionality to the default Rails link_to view helper. It provides a very simple way of adding classes to links based on the current path.
Test the path using a string/path helper:
link_to "Account", account_path, active_on: account_pathWhich, if the request.fullpath matches account_path, will result in:
<a href="/account" class="active">Account</a>Using a regular expression:
link_to "Account", account_path, active_on: /\/account/iOr a proc:
link_to "Account", account_path, active_on: lambda { request.fullpath == account_path }Any other value will cause it to be matched against the URL supplied to the link_to helper:
link_to "Account", account_path, active_on: trueBy default the class "active" will be added to the existing classes of the link. However you can specify your own:
link_to "Account", account_path, active_on: /\/account/i, active_state: "highlighted"<a href="/account" class="highlighted">Account</a>You can also customise other options by using a proc:
link_to "Account", account_path, active_on: /\/account/i, active_state: lambda { |html_options|
html_options.merge({ "data-active" => "true" })
}<a href="/account" data-active="true">Account</a>If you need an active class on an li tag, for use in a Bootstrap nav for example:
link_to "Account", account_path, active_on: account_path, active_wrapper: :liWhich will result in:
<li class="active">
<a href="/account" class="active">Account</a>
</li>Note the li tag is included as part of the html generated by the link_to helper and should not be added separately.
You can also pass a proc to the wrapper option. This takes two arguments; the generated link and the options for the wrapper (which will include the active state class):
link_to "Account", account_path,
active_on: account_path,
active_wrapper: proc { |link, wrapper_opts|
content_tag(:li, link, wrapper_opts)
}And for either of the above methods you can supply HTML attributes for the wrapper:
link_to "Account", account_path,
active_on: account_path,
active_wrapper: :li,
active_wrapper_options: { rel: "gallery" }- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request