Jak uzyskać nawigację Twitter-Bootstrap, aby pokazać aktywny link?

Nie rozumiem, jak Twitter Bootstrap robi aktywne linki do nawigacji. Jeśli mam taką zwykłą nawigację (z linkami ruby on rails):

<ul class="nav">
  <li class="active"> <a href="/link">Link</a> </li>
  <li class=""> <a href="/link">Link</a> </li>
  <li class=""> <a href="/link">Link</a> </li>        
</ul>

Jak utrzymać ją aktywną na podstawie klikniętego linku?

Author: LearningRoR, 2012-03-27

22 answers

Właśnie odpowiedziałem na to samo pytanie tutaj Twitter Bootstrap with Rails 3.2.2

<ul class="nav">
  <li class="<%= 'active' if params[:controller] == 'controller1' %>"> <a href="/link">Link</a> </li>
  <li class="<%= 'active' if params[:controller] == 'controller2' %>"> <a href="/link">Link</a> </li>
  <li class="<%= 'active' if params[:controller] == 'controller3' %>"> <a href="/link">Link</a> </li>        
</ul>
 92
Author: Pierre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:06

Możesz użyć czegoś takiego (bardzo podobnego do tego, o czym wspomniał @phil, ale trochę krótszego):

<ul class="nav">
  <li class="<%= 'active' if current_page?(root_path) %>"><%= link_to "Home", root_path %></li>
  <li class="<%= 'active' if current_page?(about_path) %>"><%= link_to "About", about_path %></li>
  <li class="<%= 'active' if current_page?(contact_path) %>"><%= link_to "Contact", contact_path %></li>
</ul>
 163
Author: yorch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-27 14:44:31

Https://github.com/twg/active_link_to

<%= active_link_to 'Users', users_path, :wrap_tag => :li %>

#=> <li class="active"><a href="/users">Users</a></li>

 45
Author: Hesham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-04 17:48:11

Użyłem helpera do zaimplementowania tego w stylu helperów form Rails.

W pomocniku (np. app/helpers/ApplicationHelper.rb):

def nav_bar
  content_tag(:ul, class: "nav navbar-nav") do
    yield
  end
end

def nav_link(text, path)
  options = current_page?(path) ? { class: "active" } : {}
  content_tag(:li, options) do
    link_to text, path
  end
end

Następnie w widoku (np. app/views/layouts/application.html.erb):

<%= nav_bar do %>
  <%= nav_link 'Home', root_path %>
  <%= nav_link 'Posts', posts_path %>
  <%= nav_link 'Users', users_path %>
<% end %>

Ten przykład tworzy (gdy na stronie 'użytkownicy'):

<ul class="nav navbar-nav">
  <li><a href="/">Home</a></li>
  <li><a href="/posts">Posts</a></li>
  <li class="active"><a href="/users">Users</a></li>
</ul>
 30
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-07 08:30:06

Użyj tego zamiast tego, aby wybrać aktywne łącze w nav na podstawie bieżącej trasy bez kodu serwera:

    $(document).ready(function () {
        $('a[href="' + this.location.pathname + '"]').parent().addClass('active');
    });
 21
Author: Christian Landgren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-14 08:46:34

Znalazłem sukces używając logicznego i (&&) W haml :

%ul.nav
  %li{class: current_page?(events_path) && 'active'}
    = link_to "Events", events_path
  %li{class: current_page?(about_path) && 'active'}
    = link_to "About Us", about_path
 11
Author: Meltemi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-15 16:58:19

Dla każdego linku:

<% if current_page?(home_path) -%><li class="active"><% else -%><li><% end -%>
  <%= link_to 'Home', home_path %>
</li>

Lub nawet

<li <% if current_page?(home_path) -%>class="active"<% end -%>>
  <%= link_to 'Home', home_path %>
</li>
 5
Author: phil pirozhkov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-02 12:10:55

Nie jestem pewien, czy pytasz o to, jak używany jest twitter Bootstrap css, czy o stronę rails. Zakładam, że od strony szyn.

Jeśli tak to sprawdź #link_to_if metoda lub #link_to_unless_current Metoda

 3
Author: cpjolicoeur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-26 20:20:19

Dzisiaj miałem to samo pytanie/problem, ale z innym podejściem do rozwiązania. Tworzę funkcję pomocnika w application_helper.rb:

def navMainAktiv(actionName)
    if params[:action] == actionName    
    "active"
    end
end

A link wygląda tak:

<li class="<%= navMainAktiv('about')%>"><%= link_to "About", about_path %></li>

Możesz zamienić params[:action] na params[:controller] i ustawić nazwę kontrolera w linku.

 3
Author: glenn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-07 02:01:29

Używam tego dla każdego li:

<li><%= link_to_unless_current('Home', root_path) { link_to('Home', root_path, class: 'active') } %></li>

 2
Author: andreofthecape,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-24 14:03:15

Możesz zdefiniować metodę pomocniczą w application_helper.rb

def create_link(text, path)
  class_name = current_page?(path) ? 'active' : ''

  content_tag(:li, class: class_name) do
    link_to text, path
  end
end

Teraz możesz użyć jak:

create_link 'xyz', any_path które renderowałyby jako

<li class="active">
  <a href="/any">xyz</a>
</li>
Mam nadzieję, że to pomoże!
 2
Author: Dusht,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-20 08:48:09

Powinieneś zrobić to sam, manipulując klasami CSS. Oznacza to, że jeśli użytkownik kliknie jakiś link, zrób coś (akcja docelowa), Ustaw poprzedni link nieaktywny i nowy link aktywny.

Jeśli twoje linki prowadzą cię do serwera (czyli powodują przeładowanie strony), możesz po prostu prawidłowo renderować aktywny link na serwerze. W przeciwnym razie, jeśli robisz rzeczy po stronie klienta (przełączanie paneli kart lub cokolwiek innego), musisz użyć javascript.

 1
Author: Sergio Tulentsev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-26 20:20:34

Możesz użyć tabulatory dla linków

Artykuł tutaj o tym, jak połączyć tabulous z twitter bootstrap i rails 3.x

 1
Author: stephenmurdoch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-26 20:33:13

Napisałem prostą metodę helpera używając build in view helper current_page?, Kiedy można podać własną nazwę class w haśle html_options.

def active_link_to(name = nil, options = nil, html_options = nil, &block)
  active_class = html_options[:active] || "active"
  html_options.delete(:active)
  html_options[:class] = "#{html_options[:class]} #{active_class}" if current_page?(options)
  link_to(name, options, html_options, &block)
end

Przykłady (gdy jesteś na root_path trasie):

<%= active_link_to "Main", root_path %>
# <a href="/" class="active">Main</a>

<%= active_link_to "Main", root_path, class: "bordered" %>
# <a href="/" class="bordered active">Main</a>

<%= active_link_to "Main", root_path, class: "bordered", active: "disabled" %>
# <a href="/" class="bordered disabled">Main</a>
 1
Author: cintrzyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-31 12:17:03

Wiele odpowiedzi tutaj mają rzeczy, które będą działać, lub częściowe odpowiedzi. Połączyłem kilka rzeczy, aby użyć tej metody pomocniczej rails:

# helper to make bootstrap3 nav-pill <li>'s with links in them, that have
# proper 'active' class if active. 
#
# the current pill will have 'active' tag on the <li>
#
# html_options param will apply to <li>, not <a>. 
#
# can pass block which will be given to `link_to` as normal. 
def bootstrap_pill_link_to(label, link_params, html_options = {})
  current = current_page?(link_params)

  if current
    html_options[:class] ||= ""
    html_options[:class] << " active "
  end

  content_tag(:li, html_options) do
    link_to(label, link_params)
  end      
end

Może być jeszcze bardziej fantazyjne z sprawdzaniem argumentów do obsługi &block na link_to itp.

 1
Author: jrochkind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-12 16:07:22

Już wiele odpowiedzi, ale oto, co napisałem, aby ikony Bootstrap działały z aktywnym linkiem. Mam nadzieję, że to komuś pomoże

Ten Pomocnik da ci:

  1. li element z linkiem zawierającym własny tekst
  2. Opcjonalna Ikona Bootstrap3
  3. włącza się, gdy jesteś na prawej stronie

Umieść to w swoim application_helper.rb

def nav_link(link_text, link_path, icon='')
  class_name = current_page?(link_path) ? 'active' : ''
  icon_class = "glyphicon glyphicon-" + icon

  content_tag(:li, :class => class_name) do
    (class_name == '') ? (link_to content_tag(:span, " "+link_text, class: icon_class), link_path)
    : (link_to content_tag(:span, " "+link_text, class: icon_class), '#')
  end
end

I użyj linku:

<%= nav_link 'Home', root_path, 'home'  %>

Ostatni argument jest opcjonalny - doda ikonę Do linku. Użyj nazw ikon glifów. Jeśli chcesz ikonę bez tekstu:

    <%= nav_link '', root_path, 'home'  %>
 1
Author: Lukasz Muzyka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-19 07:40:37

Brzmisz jakbyś potrzebował zaimplementować system nawigacji. Jeśli to skomplikowane, może stać się dość brzydkie i dość szybko.

W tym przypadku możesz użyć wtyczki, która może sobie z tym poradzić. Możesz użyć navigasmic lub prostej nawigacji (polecam navigasmic, ponieważ utrzymuje główną warstwę w widoku, gdzie należy, a nie w jakiejś konfiguracji)

 0
Author: Andrei S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-26 20:25:50

Najkrótszy kod

Dotyczy to zarówno elementów listy nav, jak i sub nav. Możesz przekazać tablicę pojedynczą ścieżką i poradzić sobie z obydwoma.

Application_helper

# Active page method
def ap(p:);'active' if p.class == Array ? p.map{|m| current_page? m}.any? : (current_page? p) end

Widok (html.erb)

<ul class="nav navbar-nav">
  <li class="<%= ap p: home_path %>">Home</li>
  <li class="<%= ap p: account_path %>">Account</li>

  <li class="dropdown <%= ap p: [users_path, new_user_path] %>">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Users</a>
    <ul class="dropdown-menu" role="menu">
      <li class="<%= ap p: users_path %>">Users</li>
      <li class="<%= ap p: new_user_path %>">Add user</li>
    </ul>
  </li>
</ul>
 0
Author: cb24,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-22 12:17:18

Używanie ruby na Sinatrze ..

Używam Bootstrap bare theme, oto przykładowy kod navbar. Zwróć uwagę na nazwę klasy elementu -> .nav - jak to określa java script.

/ Collect the nav links, forms, and other content for toggling
    #bs-example-navbar-collapse-1.collapse.navbar-collapse
      %ul.nav.navbar-nav
        %li
          %a{:href => "/demo/one"} Page One
        %li
          %a{:href => "/demo/two"} Page Two
        %li
          %a{:href => "/demo/three"} Page Three

W widoku strony (lub częściowej) dodaj to: javascript, to musi być wykonywane przy każdym ładowaniu strony.

Haml view snippet - >

- content_for :javascript do
  :javascript
      $(function () {
          $.each($('.nav').find('li'), function() {
              $(this).toggleClass('active',
                  $(this).find('a').attr('href') == window.location.pathname);
          });
      });

W debuggerze javascript upewnij się, że wartość atrybutu 'href' pasuje do okna.miejsce.pathname. To jest nieco inne niż rozwiązanie @Zitrax, które pomogło mi naprawić mój problem.

 0
Author: Rishi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-02 22:36:20

Basic, No Helper

<%= content_tag(:li, class: ('active' if request.path == '/contact')) do %>
    <%= link_to 'Contact', '/contact' %>
<% end %>

Używam tego, ponieważ mam więcej niż jedną klasę-

<%= content_tag(:li, class: (request.path == '/contact' ? 'active black' : 'black')) do %>
    <%= link_to 'Contact', '/contact' %>
<% end %>
 0
Author: scottkekoa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-21 15:14:15

Oto co zrobiłem:

Utworzyłem ViewsHelper i włączyłem do ApplicationController:

include ViewsHelper

Wewnątrz Viewshelpera stworzyłem prostą metodę taką jak Ta:

def page_state(path)
  current_page?(path) ? 'active' : ''
end

Moim zdaniem robię to:

<li class="<%= page_state(foobar_path) %>"><%= link_to 'Foobars', foobar_path %></li>
 0
Author: Nick Res,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-16 15:35:10
  def active_navigation?(controllers_name, actions_name)
   'active' if controllers_name.include?(controller_name) && actions_name.include?(action_name)
  end

Slim

li class=(active_navigation?(['events'], ['index', 'show'])) = link_to t('navbar.events'), events_path
 0
Author: Nazar Hlynskyi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-18 12:11:41