如何在Rails中为所有活动链接添加“active”类?

19
基本上,我有很多这样的代码:
link_to t('.profile'), business_path(@business), class: '#{'active' if current_page? business_path(@business)}'

这并不是很DRY。

我想知道是否有好的方法可以修改link_to帮助程序本身,以自动将所有链接到当前页面的链接添加一个“active”类。

如果有帮助的话,我可以使用HAML或SLIM。


1
根据Rails 6.1的更新,现在我们有一个HTML类名检查器的帮助程序,链接分别为这里这里 - buncis
13个回答

1

这是一个老问题,但找到了一个更简单的方法来做这个:

<%= link_to 'Test Page', my_portfolio_path , class: "nav-link  #{ request.path == test_page_path ? 'active' : ''  }"  %> 

'active' if request.path == test_page_path 的工作方式相同,你不需要使用三元运算符。另外,正如之前提到的,Rails 的 class_names 就是为此而设计的。 - undefined

0

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

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


-1
使用{{link1:link_to_unless_current}},然后在CSS中使其看起来像一个活动链接。

你能添加一个例子吗? - ismailarilik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接