Git Product home page Git Product logo

active_link_to's Introduction

active_link_to

Creates a link tag of the given name using a URL created by the set of options. Please see documentation for link_to, as active_link_to is basically a wrapper for it. This method accepts an optional :active parameter that dictates if the given link will have an extra css class attached that marks it as 'active'.

Gem Version Gem Downloads Build Status Gitter

Install

When installing for Rails 3/4/5 applications add this to the Gemfile: gem 'active_link_to' and run bundle install.

For older Rails apps add config.gem 'active_link_to' in config/environment.rb and run rake gems:install. Or just checkout this repo into /vendor/plugins directory.

Super Simple Example

Here's a link that will have a class attached if it happens to be rendered on page with path /users or any child of that page, like /users/123

active_link_to 'Users', '/users'
# => <a href="/users" class="active">Users</a>

This is exactly the same as:

active_link_to 'Users', '/users', active: :inclusive
# => <a href="/users" class="active">Users</a>

Active Options

Here's a list of available options that can be used as the :active value

* Boolean                         -> true | false
* Symbol                          -> :exclusive | :inclusive | :exact
* Regex                           -> /regex/
* Controller/Action Pair          -> [[:controller], [:action_a, :action_b]]
* Controller/Specific Action Pair -> [controller: :action_a, controller_b: :action_b]
* Hash                            -> { param_a: 1, param_b: 2 }

More Examples

Most of the functionality of active_link_to depends on the current url. Specifically, request.original_fullpath value. We covered the basic example already, so let's try something more fun.

We want to highlight a link that matches immediate url, but not the children nodes. Most commonly used for 'home' links.

# For URL: /users will be active
active_link_to 'Users', users_path, active: :exclusive
# => <a href="/users" class="active">Users</a>
# But for URL: /users/123 it will not be active
active_link_to 'Users', users_path, active: :exclusive
# => <a href="/users">Users</a>

If we need to set link to be active based on some regular expression, we can do that as well. Let's try to activate links urls of which begin with 'use':

active_link_to 'Users', users_path, active: /^\/use/

If we need to set link to be active based on an exact match, for example on filter made via a query string, we can do that as well:

active_link_to 'Users', users_path(role_eq: 'admin'), active: :exact

What if we need to mark link active for all URLs that match a particular controller, or action, or both? Or any number of those at the same time? Sure, why not:

# For matching multiple controllers and actions:
active_link_to 'User Edit', edit_user_path(@user), active: [['people', 'news'], ['show', 'edit']]

# For matching specific controllers and actions:
active_link_to 'User Edit', edit_user_path(@user), active: [people: :show, news: :edit]

# for matching all actions under given controllers:
active_link_to 'User Edit', edit_user_path(@user), active: [['people', 'news'], []]

# for matching all controllers for a particular action
active_link_to 'User Edit', edit_user_path(@user), active: [[], ['edit']]

Sometimes it should be as easy as giving link true or false value:

active_link_to 'Users', users_path, active: true

If we need to set link to be active based on params, we can do that as well:

active_link_to 'Admin users', users_path(role_eq: 'admin'), active: { role_eq: 'admin' }

More Options

You can specify active and inactive css classes for links:

active_link_to 'Users', users_path, class_active: 'enabled'
# => <a href="/users" class="enabled">Users</a>

active_link_to 'News', news_path, class_inactive: 'disabled'
# => <a href="/news" class="disabled">News</a>

Sometimes you want to replace link tag with a span if it's active:

active_link_to 'Users', users_path, active_disable: true
# => <span class="active">Users</span>

If you are constructing navigation menu it might be helpful to wrap links in another tag, like <li>:

active_link_to 'Users', users_path, wrap_tag: :li
# => <li class="active"><a href="/users">Users</a></li>

You can specify css classes for the wrap_tag:

active_link_to 'Users', users_path, wrap_tag: :li, wrap_class: 'nav-item'
# => <li class="nav-item active"><a href="/users">Users</a></li>

Helper Methods

You may directly use methods that active_link_to relies on.

is_active_link? will return true or false based on the URL and value of the :active parameter:

is_active_link?(users_path, :inclusive)
# => true

active_link_to_class will return the css class:

active_link_to_class(users_path, active: :inclusive)
# => 'active'

Copyright

Copyright (c) 2009-18 Oleg Khabarov. See LICENSE for details.

active_link_to's People

Contributors

alecrust avatar amatsuda avatar cerebroso avatar chrise86 avatar davekrupinski avatar fustrate avatar gbh avatar haggen avatar maschwenk avatar maurogeorge avatar mhayes avatar pluff avatar seanpdoyle avatar tricknotes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active_link_to's Issues

Using with html_options param seems to break :active => :exclusive

When trying to add to class string using html_options param from link_to, adding :active => :exclusive doesn't seem to be working: my root link is always active, but only when including this classing object.

<%= active_link_to "Home", root_path, { :class => 'nav-link' }, :active => :exclusive %>

Wrap link in content_tag?

It's be really awesome if the generated link could be wrapped in a user defined content tag. So for example I'd like to use this plugin as follows:

active_link_to 'People', '/people', :wrap_tag => :li

=>
  • People
  • Could this functionality be added?

    disable_link should respect when condition

    Hi,
    I have a little problem with using active_link_to. I would expect when when condition is set :self_only so disable_link respect this condition. Both paths has same controller name and just different actions. In my case this behaves differently than I expect

    This is just demonstrative example

    = active_link_to 'My view',   my_view_path,   active:  { when: :self_only, disable_link: true }
    = active_link_to 'Neighbour  view', neighbour_view_path, active: { when: :self_only, disable_link: true }

    nested active_link_to inside block

    Hi guys,

    I got myself a problem, I have active_link_to inside active_link_to block and it is doing some weird stuff:

    This:

    <ul>
      <% @sites.roots.each do |root_site|%>
        <%= active_link_to site_path(root_site), wrap_tag: :li, class: "#{!root_site.descendants.empty? ? 'sub open-sub' : ''}" do %>
          <%= root_site.name %>
          <% unless root_site.descendants.empty? %>
            <ul>    
              <% root_site.descendants.each do |site| %>
                <%= active_link_to site.name, site_path(site), wrap_tag: :li %>
              <% end %>
            </ul>    
          <% end %>
        <% end %>
      <% end %>
    </ul>

    generates this HTML:

    <ul>
      <li class="sub open-sub">
        <a class="sub open-sub" href="/o-spolecnosti">O společnosti</a>
        <ul>
          <a class="sub open-sub" href="/o-spolecnosti"></a>
          <li>
            <a class="sub open-sub" href="/o-spolecnosti"></a>
            <a href="/volna-mista">Volná místa</a>
          </li>
          <li><a href="/kontakt">Kontakt</a></li>
        </ul>    
      </li>          
      <li><a href="/reference">Reference</a></li>          
      <li class="active"><a class="active" href="/prodej-na-splatky">Prodej na splátky</a></li>          
      <li><a href="/zelena-usporam">Zelená úsporám</a></li>          
      <li><a href="/zarucni-a-pozarucni-servis">Záruční a pozáruční servis</a></li>          
      <li><a href="/zednicke-prace">Zednické práce</a></li>          
      <li><a href="/mapa-stranek">Mapa stránek</a></li>          
      <li><a href="/test-stranek">Test stránek</a></li>      
    </ul>

    you can see that <a class="sub open-sub" href="/o-spolecnosti"> is there in all the layers, from where it should be to children.... that is not what I wanted, I wanted:

    <ul>
      <li class="sub open-sub">
        <a class="sub open-sub" href="/o-spolecnosti">O společnosti</a>
        <ul>
          <li><a href="/volna-mista">Volná místa</a></li>
          <li><a href="/kontakt">Kontakt</a></li>
       </ul>    
      </li>          
      <li><a href="/reference">Reference</a></li>          
      <li class="active"><a class="active" href="/prodej-na-splatky">Prodej na splátky</a></li>          
      <li><a href="/zelena-usporam">Zelená úsporám</a></li>          
      <li><a href="/zarucni-a-pozarucni-servis">Záruční a pozáruční servis</a></li>          
      <li><a href="/zednicke-prace">Zednické práce</a></li>          
      <li><a href="/mapa-stranek">Mapa stránek</a></li>          
      <li><a href="/test-stranek">Test stránek</a></li>      
    </ul>

    any help at all would be appreciated, THX :)

    Allow symbols for controller/action pair

    According to the docs, controller/action pair can be used with symbols, but its not working.

    Controller/Action Pair          -> [[:controller], [:action_a, :action_b]]
    

    The examples shows it should be use as strings:

    active_link_to 'User Edit', edit_user_path(@user), active: [['people', 'news'], ['show', 'edit']]
    

    It's confused when you can use [controller: :action], but not [[:controller], [:action]].

    Add sr-only span alerting screen readers to link's "active" nature

    Bootstrap now recommends adding a span alerting screenreaders to a link's active status, i.e.

    <li class="active">
      <a href="#">
        Link <span class="sr-only">(current)</span>
      </a>
    </li>
    

    since the screen readers would otherwise have no indication.

    Would this be an acceptable default for this repo?

    Support overloading parameter based predicate

    Summary

    The params based active predicate can be extended to support overloading param values.

    e.g. active_link_to 'Link', some_path, active: { param: ['one', 'two'] }

    This would allow a link to be active if a specific parameter is either 'one' or 'two'.

    How to use on name spaced routes?

    I have controllers which use the admin namespace, how do you match the routes then?

    for example:

    active_link_to 'User Edit', edit_user_path(@user), active: [['admin/users', 'admin/userstuff'], []]

    Set active and inactive class name globally

    I'm using Bulma in a project where the active class is is-active instead of just active. It would be nice to be able to set this globally rather than specifying class_active: 'is-active' on each invocation.

    I'm out of time for today but I'll see if I can throw together a PR that does this.

    Add arbitrary attribute

    I want to add aria-selected: true when link is active, is there a way to do so with this gem?

    Add support for links with hashes

    Hi!

    This might be possible already, but it does not seem to be working for me.

    I have the following:

    active_link_to "Emissions", city_path(city, anchor: "#city-emissions") but the presence of the hash is not triggering the link activation.

    I have tired active: :inclusive, active: :exclusive, and active: :exact.

    Any tips?

    Thanks

    Exclude controller/action

    It would be nice if it was possible exclude certain actions. :active => [['people']], :exclude => [[], ['dashboard'] ].

    This will solve my problem of wanting a link active with just one action. The second link should be active for all other actions:
    :active => [['people'], ['dashboard'] ]
    :active => [['people']], :exclude => [[], ['dashboard'] ]

    Not sure how big this issue is as it can be solved by manually typing in all other actions.

    UTF-8 support

    Latest version (1.0.3) does not appear to support UTF-8 characters in a URL. Calling is_active_link? on something with special characters (i.e. "http://abc.de/äöü"), results in an error.

    Workaround is to just call URI.encode(url) b/f passing to gem.

    Having issues with Rails 5.2

    I need you to look into why its not resolving for Rails 5.2. The message I am receiving is below.

    Bundler could not find compatible versions for gem "actionpack":
    
      In Gemfile:
        active_link_to x64-mingw32 was resolved to 1.0.5, which depends on
          actionpack x64-mingw32
    
    

    Typos

    Hello, You have typos in the Readme file in line below:

    active_link_to 'Users', users_path, :disable_active => true
    instead of disable_active should be active_disable. I have found this in Your source.

    Thanks for this usefull gem.

    Ruslan Kuzma.

    Nothing works if link is an absolute url.

    URL: http://localhost/welcome
    Link: = active_link_to 'Welcome', '/wecome' Active!
    Link: = active_link_to 'Welcome', 'http://localhost/wecome' Not active
    Link: = active_link_to 'Welcome', '//localhost/wecome' Not active

    Would be nice if it could deal with absolute urls

    active_link_to yields to blocks

    Hello again Comfy,

    Thank you for your great gem. It's been very handy. I was wondering if you would accept a pull request for active_link_to to yield to blocks if it's an active link. Here is my use case.

    <%= active_link_to 'Some Path', some_path(@path) do %>
      <nav>Sub Navigation For Active Tab</nav>
    <% end %

    If not, no worries. I understand this might bloat your gem.

    Wrapper active class

    Thanks for your work.
    Would be nice to be able to set wrapper_active_class as well, especially if wrap_tag is present.

    active_link_to 'Home' root_path is always active

    Creating a active_link_to 'Home' root_path makes it always active, no mather which path I am in.

    For example, if I visit my active_link_to 'Books' books_path, then both the Books and the Home link get the active class.

    Tested with rails 5.0.0.1 and active_link_to 1.0.3.

    Strange behavior

    I have following routes in my app:

    admin_users => GET/admin/users(.:format) => admin/users#index
    admin_root => GET /admin(.:format) => admin/welcome#index
    

    And following markup:

    = active_link_to 'Main', admin_root_path, wrap_tag: 'li'
    = active_link_to 'Users', admin_users_path, wrap_tag: 'li'

    And here comes the problem: then i visit "Main" page - everything is ok, class="active". But then i visit "Users" page - "Main" link also gets "active" class. Wtf?

    Clarify usage with namespaced controllers

    Hi,

    i am trying to use active_link_to for the index and show action of a namespaced controller.

    /admin/documents => true
    /admin/documents/1 => true
    /admin/documents/new => false

    My code:

    <%= active_link_to "Dokumente zur Freigabe (5)", admin_documents_path(published: false), class_active: "is-active", active: [['admin/documents'], [:index, :show]] %>
    

    Any ideas why this is not working? Thank you! :)

    Nested Controllers

    Hi Comfy,

    Based on a few tests, I don't believe the active option handles nested controllers correctly.

    # url: http://localhost:3000/invitations/new
    # routes.rb
    scope module: 'organizations' do
      resources :invitations, only:  [:new, :create] do
        ...
      end
    end
    
    # View attempts:
    <%= active_link_to 'Accounts', accounts_path, active: [['organizations::invitations'], ['new']] %>
    <%= active_link_to 'Accounts', accounts_path, active: [['invitations'], ['new']] %>

    Bug

    Link to root page always blank if active_disable == true

    Support nested params

    Add support nested params. For example:

    /events?filter%5Bname%5D=sent+message
    
    <%= active_link_to(_('Sent message'),
                             events_url(filter: { name: 'sent message' }),
                             class_active: 'current',
                             active: { filter: { name: 'sent message' } },
                             wrap_tag: :li ) %>
    

    Option for nested links

    Hi. I have a url that looks kind of like this:

    http://tour-builder.dev/tours/5/stops/15/photos/new

    As is, the active_link_to is only showing up with something like /tour/5/stops/16/edit I would like it to show up with both. Is there a way or a setting to do this? My navigation that has this active_link_to is in a partial that gets shared with my photos and stops template.

    I think I can get around this with a regular expression but I believe in your explanation it should be making the link active if any chidden of my link are matched. This is what my code looks like that generates it.

          <%= active_link_to stop.name, edit_tour_stop_path(tour, stop) %>
    

    Thanks!

    What's changed between v1.0.2 and v1.0.3?

    I just upgraded from v1.0.3 from v1.0.2 and I'm experiencing different behaviour (I've built navigation that uses this active_link_to helpers extensively).

    I'm not here to file a complaint really, just a request that the project have a CHANGELOG to show what's been changed/added. Tried looking through the commits and it's a difficult trying to trace all this down especially since a lot of the commits aren't very descriptive as to what's being done.

    This way, I can be in a better position to debug and hopefully trace down and articulate what the problem/fix is/could be. Meanwhile, I've rolled back to v1.0.2.

    root path?

    Question: my page can be accessed as root_path ("/") and a specific url ("/procedures"), how do i specify that?

    Testing active_link_to

    Hey there, my team uses active_link_to pretty extensively to manage our navigation links. Today I was writing out some pretty complex logic surrounding a nav menu that uses active_link_to, but I couldn't figure out how to test the results.

    I mirrored your tests by doing

    require 'active_link_to'
    

    Before my tests, but I keep getting NoMethod errors every time it hits an active_link_to call.

    What way would I go about testing this gem within my app, without mocking the entire gem?

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google ❤️ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.