Twitter-Bootstrap 탐색을 통해 활성 링크를 표시하는 방법은 무엇입니까?


106

Twitter Bootstrap이 탐색을 위해 활성 링크를 수행하는 방법을 이해하지 못합니다. 다음과 같은 일반 내비게이션이있는 경우 (레일 연결에 루비 포함) :

<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>

클릭 한 링크를 기반으로 활성 상태를 유지하려면 어떻게합니까?


1
참고 : active_link_to gem을 사용하고 {: wrap_class => : li}를 지정합니다. REQUEST_URI가 HREF 값과 일치하면 <li class = 'active'> ... </ li>가 생성됩니다.
Justin E

답변:


95

여기에서 바로 동일한 질문에 대한 답변을했습니다. Twitter Bootstrap Pills 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>

21
나는 여기에서 아이디어가 정확하다고 생각하지만 params 해시로 직접 이동하는 것은 나쁜 생각처럼 보입니다. 같은 코드를 계속 반복하는 경우에도 마찬가지입니다. 적어도 current_page를 사용하는 것이 좋습니다. 메서드를 사용하여 현재 컨트롤러 / 작업을 확인하고 코드 반복을 피하기 위해 코드를 도우미로 이동합니다.
Dustin Frazier

2
나는 haml에서 어떻게 똑같이 쓰는지 궁금합니다. haml로 변환하는 것은 나를 위해 작동하지 않습니다. 아니면 내가 잘못 어딘가에 해요
benchwarmer

14
HAML 구현%li{:class => "#{'active' if current_page?(root_path)}"}=link_to "Home", root_path
Brian

db 요청을하지 않고 friendly_id gem을 사용하여이 작업을 수행하는 우아한 방법이 있습니까?
Engin Erdogan 2013 년

6
Rails 문서 는 params 해시에서 액세스하는 대신 controller_nameaction_name도우미 사용을 권장합니다 .
Alexander Suraphel 2013 년

171

다음과 같은 것을 사용할 수 있습니다 (@phil이 언급 한 것과 매우 유사하지만 조금 더 짧음).

<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>

10
하위 탐색이 있으면 작동하지 않습니다. 경로는 바뀌지 만 당신은 같은 구역에 있습니다 .. 말이 되나요?
Jakob Dam Jensen

3
예, 맞습니다. 동일한 컨트롤러 내에서 어떤 방법을 실행하든 메뉴 항목을 강조 표시하려면 @Pierre 솔루션을 사용할 수 있습니다.'active' if params[:controller] == 'controller1'
yorch

예, 이것이 가장 우아한 방법입니다! 감사합니다 :)
squiter

2
어떻게 이상의 경로 또는 같은 특정 경로에 추가 할 수 user_*_path있는가 <%= 'active' if current_page?(root_path) %>?
Ismoh

1
메뉴 항목을 활성화하기 위해 둘 이상의 경로를 추가하는 방법은 무엇입니까? 예를 들어, 동일한 메뉴 항목의 구성 요소 인 드롭 다운에 여러 항목이 있고 드롭 다운 메뉴에있는 페이지 중 하나에있을 때 메뉴 항목을 활성화하고 싶습니까? 가능한 한 빨리 알려주십시오.
msc

47

https://github.com/twg/active_link_to

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

#=> <li class="active"><a href="https://stackoverflow.com/users">Users</a></li>


7
그것을 사랑하십시오. 휠을 다시 작성하는 이유는 무엇입니까?
lightyrs dec

이것은 정말로 갈 길이되어야합니다 ... 다른 의존성을 가져오고 싶지 않다면.
Mark G.

33

나는 이것을 Rails의 폼 헬퍼 스타일로 구현하기 위해 헬퍼를 사용했다.

도우미에서 (예 :) 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

그런 다음보기 (예 :)에서 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 %>

이 예는 다음을 생성합니다 ( '사용자'페이지에있는 경우).

<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>

대단합니다! 감사!
Krzysztof Witczak

이 아이디어가 마음에 들지만 html = {}이라는 nav_link 함수에 세 번째 인수를 추가하여 link_to에 전달합니다. 이렇게하면 일반적으로 link_to를 사용하는 것과 같은 방식으로 nav_link에 html 해시를 전달할 수 있습니다.
Ryan Friedman

22

대신 이것을 사용하여 서버 코드가없는 현재 경로를 기반으로 탐색에서 활성 링크를 선택하십시오.

    $(document).ready(function () {
        $('a[href="' + this.location.pathname + '"]').parent().addClass('active');
    });

2
이것은 드롭 다운 메뉴에서도 작동하는 최상의 솔루션이며 $('li.active').closest('.dropdown').addClass('active');상위 메뉴도 강조 표시하는 줄 을 포함합니다 .
Seralto

하위 페이지에도 적용하도록 변경하는 방법은 무엇입니까? example.com/home 과 같이 작동합니다. example.com/home/page의 경우 에도 "홈"링크가 활성화되어야 합니다.
athultuttu

11

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

5

각 링크에 대해 :

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

또는

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

3

트위터 부트 스트랩 CSS가 어떻게 사용되는지 또는 레일 측에 대해 묻는 지 확실하지 않습니다. 나는 레일 쪽을 가정하고 있습니다.

그렇다면 #link_to_if방법 또는 #link_to_unless_current방법을 확인하십시오.


3

오늘 나는 동일한 질문 / 문제가 있었지만 솔루션에 대한 다른 접근 방식을 사용했습니다. application_helper.rb에 도우미 함수를 만듭니다.

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

링크는 다음과 같습니다.

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

당신은 대체 할 수 params[:action]와 함께 params[:controller]하고 링크에서 컨트롤러의 이름을 설정합니다.


2

나는 이것을 각각 사용합니다 li.

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


클래스에 설정 될 필요가 li없습니다a
크리스토퍼 Oezbek에게

2

도우미 메서드를 정의 할 수 있습니다. 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

이제 다음과 같이 사용할 수 있습니다.

create_link 'xyz', any_path 다음과 같이 렌더링됩니다.

<li class="active">
  <a href="/any">xyz</a>
</li>

도움이 되었기를 바랍니다.


1

CSS 클래스를 조작하여 직접해야합니다. 즉, 사용자가 일부 링크를 클릭 한 다음 작업 (대상 동작)을 수행하고 이전 링크를 비활성화하고 새 링크를 활성화합니다.

링크가 서버로 이동하는 경우 (즉, 페이지를 다시로드) 서버에서 활성 링크를 올바르게 렌더링 할 수 있습니다. 그렇지 않으면 클라이언트 측 작업 (탭 창 전환 등)을 수행하는 경우 자바 스크립트를 사용해야합니다.


1

당신은 링크에 대해 를 사용할 수 있습니다

기사 여기에 트위터 부트 스트랩과 tabulous을 결합 및 3.x 레일하는 방법에


1

해시 에서 current_page?사용자 지정 class이름을 지정할 수있을 때 뷰 도우미에서 빌드를 사용하여 간단한 도우미 메서드를 작성했습니다 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

예 ( root_path경유중인 경우) :

<%= 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

여기에있는 많은 답변에는 효과가 있거나 부분적인 답변이 있습니다. 이 레일 도우미 메서드를 만들기 위해 여러 가지를 결합했습니다.

# 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

&blocklink_to 등 을 지원하기 위해 인수 검사로 더 멋지게 만들 수 있습니다 .


1

이미 많은 답변이 있지만 여기에 내가 작성한 Bootstrap Icons가 활성 링크와 함께 작동합니다. 누군가를 도울 수 있기를 바랍니다

이 도우미는 다음을 제공합니다.

  1. 사용자 정의 텍스트를 포함하는 링크가있는 li 요소
  2. 선택적 Bootstrap3 아이콘
  3. 오른쪽 페이지에있을 때 활성화됩니다.

이것을 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

그리고 링크 사용 :

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

마지막 인수는 선택 사항입니다. 링크에 아이콘을 추가합니다. 글리프 아이콘의 이름을 사용합니다. 텍스트가없는 아이콘을 원하는 경우 :

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

1

내가 한 일은 다음과 같습니다.

ViewsHelper를 만들고 ApplicationController에 포함했습니다.

include ViewsHelper

ViewsHelper 내부에서 다음과 같은 간단한 방법을 만들었습니다.

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

내 관점에서 나는 이것을한다 :

<li class="<%= page_state(foobar_path) %>"><%= link_to 'Foobars', foobar_path %></li>

0

내비게이션 시스템을 구현해야하는 것 같습니다. 복잡하다면 아주 추하고 빠르게 될 수 있습니다.

이 경우이를 처리 할 수있는 플러그인을 사용할 수 있습니다. navigasmic 또는 간단한 탐색을 사용할 수 있습니다 (일부 구성이 아닌 뷰에 기본 레이어를 유지하기 때문에 navigasmic을 권장합니다)


0

가장 짧은 코드 

이것은 탐색 및 하위 탐색 목록 요소를 모두 다룹니다. 배열 중 하나에 단일 경로를 전달할 수 있으며 둘 다 처리합니다.

application_helper

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

보기 (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

Sinatra에서 루비 사용 ..

부트 스트랩 베어 테마를 사용하고 있습니다. 여기 샘플 navbar 코드가 있습니다. 요소의 클래스 이름-> .nav-이것은 자바 스크립트에서 참조됩니다.

/ 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

보기 페이지 (또는 부분)에서 다음을 추가하십시오. : javascript, 페이지가로드 될 때마다 실행되어야합니다.

haml보기 스 니펫->

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

자바 스크립트 디버거에서 'href'속성 값이 window.location.pathname과 일치하는지 확인하세요. 이것은 내 문제를 해결하는 데 도움이 된 @Zitrax의 솔루션과 약간 다릅니다.


0

기본, 도우미 없음

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

나는 하나 이상의 수업이 있기 때문에 이것을 사용합니다.

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

1
이것은 모든 하위 탐색에서도 작동합니다 ... 하위 링크에서 상위 요청 경로를 사용하십시오.
scottkekoa

0
  def active_navigation?(controllers_name, actions_name)
   'active' if controllers_name.include?(controller_name) && actions_name.include?(action_name)
  end

날씬한

li class=(active_navigation?(['events'], ['index', 'show'])) = link_to t('navbar.events'), events_path
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.