【问题标题】:Add an 'active' class to all active links in rails?向 Rails 中的所有活动链接添加“活动”类?
【发布时间】:2013-09-09 14:56:53
【问题描述】:

基本上,我有很多这样的代码:

link_to t('.profile'), business_path(@business), class: '#{'active' if current_page? business_path(@business)}'

这不是很干燥。

我想知道是否有人知道修改 link_to 帮助器本身以自动将“活动”类添加到当前页面的所有链接的好方法。

如果有帮助,我愿意使用 HAML 或 SLIM。

【问题讨论】:

  • 根据 rails 6.1 现在我们有用于检查 html 类名的助手 thisthis

标签: css ruby-on-rails views link-to view-helpers


【解决方案1】:

当您可以在 html_options 哈希中指定自定义 class 名称时,我使用内置视图助手 current_page? 编写了简单的助手方法。

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>

【讨论】:

  • 由于 rails 的 link_to 的工作方式,当您实际将一个块传递给您的 active_link_to 时,这会中断。
【解决方案2】:

这是一个已解决的问题,只需使用active_link_to gem。您的示例简化为:

= active_link_to t('.profile'), business_path(@business)

【讨论】:

  • active_link_to 很棒。它允许您包装链接(例如使用li)并指定其他匹配条件,例如使用正则表达式。谢谢!
【解决方案3】:

我遇到了同样的要求,这是我的解决方案。

ApplicationHelper中创建一个方法

def active_class(link_path)
    current_page?(link_path) ? "active" : ""
end

在你的视野中:

    <li class="<%= active_class('/') %>">
      <%= link_to 'HOME', root_path %>
    </li>

【讨论】:

  • 这是 OP 答案最干净、最简单、最简单的解决方案。在我看来,无需为应用程序助手插入 gem。
【解决方案4】:

这是编写您自己的帮助程序来包装link_to 的好案例。在您的 application_helper.rb 中,您可以编写一个方法 active_link_to,它采用与 link_to + current_page 相同的参数,然后像上面那样调用 link_to。

【讨论】:

【解决方案5】:

这是我使用的助手。我添加了一个可选的“match_text”参数以增加灵活性(例如,如果我想在实际请求路径是链接目标的子页面时将链接标记为活动。)

def link_to_active(text, destination, options = {})
  match_text = options.delete(:match_text)

  classes = options[:class].present? ? options[:class].split(" ") : []
  classes << "active" if request.fullpath.downcase == destination.downcase || (match_text && request.fullpath.downcase.include?(match_text.downcase))

  options = options.except(:class)
  options.merge!(:class => classes.join(" ")) unless classes.empty?

  link_to(text, destination, options)
end

【讨论】:

    【解决方案6】:

    根据 rails 6.1,现在我们有 html 类名的帮助器

    辅助示例

    class_names("foo", "bar")
     # => "foo bar"
    class_names({ foo: true, bar: false })
     # => "foo"
    class_names(nil, false, 123, "", "foo", { bar: true })
     # => "123 foo bar"
    

    你可以这样使用它

    <%= link_to 'Home', root_path, class: class_names('nav-link', { active: current_page?(root_path) }) %>
    

    它会生成这样的html

    <a class="nav-link active" href="/">Home</a>
    

    文档是here

    【讨论】:

      【解决方案7】:

      我和@egyamado 做了同样的事情。我也需要使用 AwesomeIcons,所以:

      助手:

      def active_class?(link_path)
          'active' if current_page?(link_path)
      end
      

      这是我的观点:

       <%= link_to my_controller_page_path,
          :title => "My Controller Page",
          :class => "other_name_class #{active_class?(my_controller_page_path)}" do  %>
                      <i class="fa fa-fighter-jet"></i>&nbsp;My Controller Page
      <%end%>
      

      在另一种链接中,例如在 Li 中。

      #In this case I put a extra validation in root_path
      <li class="nav-class <%=active_class?(my_controller_page_path)%> <%='active' if current_page?(root_path) %>">
        <%= link_to my_controller_page_path,
            :title => "Page 1",
            :class => "other_name_class" do  %>
            Page 1
        <%end%>
      </li>
      <li class="nav-class <%=active_class?(my_controller_page_2_path)%>">
        <%= link_to my_controller_page_2_path,
            :title => "Page 2",
            :class => "other_name_class" do  %>
            Page 2
        <%end%>
      </li> 
      

      它对我有用。

      【讨论】:

        【解决方案8】:

        这是我处理此问题的自定义方法。

          def active_link_to(name = nil, options = nil, html_options = nil, &block)
            if current_page?(options)
              active_class = html_options[:active_class] ? html_options[:active_class] : 'has-text-danger'
              html_options[:class] << "#{html_options[:class]} #{active_class}"
            end
        
            link_to(name, options, html_options, &block)
          end
        

        html_options[:active_class] 是自定义哈希。

        现在我可以动态更改活动链接的样式。

        <%= active_link_to "Menu", root_path, class: 'has-text-dark', active_class: 'has-text-danger' %>
        
        

        【讨论】:

          【解决方案9】:

          这是一个可以扩展的基本示例:

          module ApplicationHelper
            def active_link_to(text, path, **opts, &block)
              css_class = opts[:class]
          
              case opts[:endpoint]
                when String then css_class.concat(' active') if current_page? opts[:endpoint]
                when Array  then css_class.concat(' active') if opts[:endpoint].include? request.path
              end
          
              if block_given?
                link_to path, class: css_class, &block
              else
                link_to text, path, class: css_class
              end
            end
          end
          
          # app/views/layout/_navbar.html.erb
          
          # Using multiple endpoints
          <%= active_link_to 'Home',  root_path,  class: 'some-class', endpoint: ['', '/', '/home'] %>
          
          # Using a single endpoint
          <%= active_link_to 'Admin', admin_path, class: 'some-class', endpoint: '/admin' %>
          
          # Using a block
          <%= active_link_to admin_path, class: 'some-class', endpoint: '/admin' do %>
            <h1>Administration</h1>
          <% end %>
          

          【讨论】:

            【解决方案10】:

            使用link_to_unless_current,然后让它看起来像 CSS 中的活动链接。

            【讨论】:

            • 你能举个例子吗?
            猜你喜欢
            • 2017-11-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-12-25
            • 2017-08-23
            相关资源
            最近更新 更多