Возникла проблема с реализацией выделения текущей ссылки - PullRequest
0 голосов
/ 28 марта 2011

После этого фрагмента я настроил в своем приложении rails подсветку текущей ссылки, которая отображается.

<div class="env-alt rtl">
  <%= section_link( "Home", :controller => 'welcome' ) %> |
    <% if user_signed_in? %>
      <%= section_link( "Map", :controller => 'pois' ) %> |
      <%= section_link( "News", :controller => 'news', :ref => 'home' ) %> |
      <%= section_link( "Documents", :controller => 'documents', :ref => 'home' ) %> |
      <%= section_link( "Organisations", :controller => 'organisations', :ref => 'home' ) %> |
        <%= section_link( "Dashboard", :controller => 'welcome', :action => 'dashboard' ) %> |
    <%#= link_to "Sign out", destroy_user_session_path, :id => 'sign_out' %>
    <% else %>
    <%= link_to "Sign up", new_user_registration_path, :id => 'sign_up' %> |
    <%= link_to "Sign in", new_user_session_path, :id => 'sign_in' %>
    <% end %>
</div>

В application_controller.rb у меня есть следующее:

def instantiate_controller_and_action_names
    @current_action         = action_name
    @current_controller = controller_name
end

В application_helper.rb:

def section_link(name, options)
    action      = options[:action] || 'index'
    controller  = options[:controller]

    if action.eql?(@current_action) and controller.eql?(@current_controller)
        link_to(name, options, :class => 'youarehere')
    else
    link_to(name, options)
    end
end

Я думаю, у меня все настроеноправильно.Однако, это выдает мне странную ошибку:

Showing /home/syed/work/projects/mapunity/environment/app/views/shared/links/_user.erb where line #2 raised:

No route matches {:controller=>"devise/welcome"}

Extracted source (around line #2):

1: <div class="env-alt rtl">
2:   <%= section_link( "Home", :controller => 'welcome' ) %> |
3:  <% if user_signed_in? %>
4:    <%= section_link( "Map", :controller => 'pois' ) %> |
5:    <%= section_link( "News", :controller => 'news', :ref => 'home' ) %> |

Почему автоматически добавляется :controller => "devise/welcome"?Любые указатели на то, где я иду не так, будут оценены.Заранее спасибо.

1 Ответ

0 голосов
/ 15 июня 2011

Отвечая на мой собственный вопрос, может быть полезным для кого-то другого, нужно обновить моего помощника section_link_to следующим образом:

Определил класс css .current, чтобы выделить текущую ссылку.Мое определение выглядит так:

.current {
    font-size: 12pt;
    text-decoration: none;
}

В application_controller.rb определите before_filter, который установит имена текущего контроллера и действия.

def instantiate_controller_and_action_names
  @current_action = action_name
  @current_controller = controller_name
end

Затем помощник:

def section_link_to(name, url_options, html_options = {})
  if url_options.is_a?(Hash)
    action = url_options[:action] || 'index'        
    controller = url_options[:controller]

    if action.eql?(@current_action) and controller.eql?(@current_controller)
      link_to(name, url_options, html_options, :class => 'current')
    else
      link_to(name, url_options, html_options)
    end
  else
    if url_options.length > 1
      controller = url_options.delete('/')
      if controller.include?('?')
        controller = controller.split('?')[0]
      end
    else 
      controller = 'welcome' 
    end

    if controller == @current_controller
      if html_options.has_key?(:class)
        css_options = html_options.fetch(:class)
        css_options << ' current'

        html_options.merge!( { :class => css_options })
      else
        html_options.merge!( { :class => 'current' } )
      end

      link_to(name, url_options, html_options)
    else
      link_to(name, url_options, html_options)
    end
  end
end

В помощнике я проверяю, равны ли current_controller и current_action ссылка, которая отображается.Если да, добавьте класс .current к этой ссылке и выполните рендеринг.

Теперь я могу передать либо хэш опций, таких как:

<%= section_link_to "Home", :controller => 'welcome %>

, либо использовать сгенерированные рельсы следующим образом:

<%= section_link_to "Home", root_path %>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...