[navigation] Rails 3에서 탐색에 “현재”클래스를 추가하는 가장 좋은 방법

탐색 메뉴에 일부 정적 페이지가 있습니다. 현재 표시중인 항목에 “current”와 같은 클래스를 추가하고 싶습니다.

내가하는 방법은 컨트롤러와 동작을 확인하기 위해 수많은 도우미 메서드 (각 항목에 대해)를 추가하는 것입니다.

def current_root_class
  'class="current"' if controller_name == "homepage" && action_name == "index"
end

<ul>
  <li <%= current_root_class %>><%= link_to "Home", root_path %>

그렇게하는 더 좋은 방법이 있습니까!? 지금 내 방식이 너무 멍청 해 ……



답변

나는 당신과 똑같은 방식으로 사용하고 있기 때문에 여기에서 진정한 답은 아닙니다. 여러 컨트롤러 또는 작업을 테스트하기 위해 도우미 메서드를 정의했습니다.

application_helper.rb에서

  def controller?(*controller)
    controller.include?(params[:controller])
  end

  def action?(*action)
    action.include?(params[:action])
  end

그런 다음 if controller?("homepage") && action?("index", "show")뷰 또는 기타 도우미 메서드에서 사용할 수 있습니다 .


답변

나는 도우미를 만들었습니다 nav_link.

def nav_link(link_text, link_path)
  class_name = current_page?(link_path) ? 'current' : ''

  content_tag(:li, :class => class_name) do
    link_to link_text, link_path
  end
end

다음과 같이 사용 :

nav_link 'Home', root_path

다음과 같은 HTML을 생성합니다.

<li class="current"><a href="/">Home</a></li>


답변

current_page?도우미를 사용하여 "current"클래스를 할당해야하는지 여부를 결정합니다 . 예를 들면 :

<%= 'active' if current_page?(home_about_path) %>

경로 (옵션 해시뿐만 아니라)도 전달할 수 있습니다 current_page?(root_path). 예 : .


답변

이 nav_link (text, link) 함수를 application_helper.rb (Rails 3)에서 사용하여 작업을 완료하고 내 부트 스트랩 twitter 2.0 탐색 모음 링크를 제공합니다.

def nav_link(text, link)
    recognized = Rails.application.routes.recognize_path(link)
    if recognized[:controller] == params[:controller] && recognized[:action] == params[:action]
        content_tag(:li, :class => "active") do
            link_to( text, link)
        end
    else
        content_tag(:li) do
            link_to( text, link)
        end
    end
end

예:

<%=nav_link("About Us", about_path) %>


답변

내가 한 방법은 application_helper에 도우미 함수를 추가하는 것입니다.

def current_class?(test_path)
  return 'current' if request.request_uri == test_path
  ''
end

그런 다음 탐색에서

<%= link_to 'Home', root_path, :class => current_class?(root_path) %>

이것은 현재 페이지 URI에 대한 링크 경로를 테스트하고 현재 클래스 또는 빈 문자열을 반환합니다.

나는 이것을 철저히 테스트하지 않았고 RoR (PHP로 10 년 후에 이동)을 처음 접했기 때문에 이것이 중대한 결함이 있다면 듣고 싶습니다.

적어도 이렇게하면 각 링크에서 하나의 도우미 함수와 간단한 호출 만 필요합니다.


답변

@Skilldrick의 답변을 구축하려면 …

이 코드를 application.js에 추가하면 활성 자식이있는 드롭 다운 메뉴도 활성으로 표시됩니다.

$('.active').closest('li.dropdown').addClass('active');

지원 코드를 요약하려면> nav_link라는 도우미를 추가합니다.

def nav_link_to(link_text, link_path)
  class_name = current_page?(link_path) ? 'active' : ''

  content_tag(:li, :class => class_name) do
    link_to link_text, link_path
  end
end

다음과 같이 사용 :

nav_link_to 'Home', root_path

다음과 같은 HTML을 생성합니다.

<li class="active"><a href="/">Home</a></li>


답변

가장 좋은 방법은

application_helper.rb :

def is_active(controller, action)
  params[:action] == action && params[:controller] == controller ? "active" : nil
end

그리고 메뉴 :

<li class="<%= is_active('controller', 'action') %>">