Dyl*_*arr 13 css views ruby-on-rails view-helpers link-to
基本上,我有很多看起来像这样的代码:
link_to t('.profile'), business_path(@business), class: '#{'active' if current_page? business_path(@business)}'
Run Code Online (Sandbox Code Playgroud)
这不是很干.
我想知道是否有人知道修改link_to帮助程序本身的好方法,以自动将"活动"类添加到当前页面的所有链接.
如果它有帮助,我愿意使用HAML或SLIM.
cin*_*zyk 15
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
Run Code Online (Sandbox Code Playgroud)
示例(当您在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>
Run Code Online (Sandbox Code Playgroud)
Gro*_*ery 13
这是一个解决的问题,只需使用active_link_to gem.您的示例简化为:
= active_link_to t('.profile'), business_path(@business)
Run Code Online (Sandbox Code Playgroud)
egy*_*ado 12
我遇到了同样的要求,这是我的解决方案。
在里面创建一个方法 ApplicationHelper
def active_class(link_path)
current_page?(link_path) ? "active" : ""
end
Run Code Online (Sandbox Code Playgroud)
在你的观点中:
<li class="<%= active_class('/') %>">
<%= link_to 'HOME', root_path %>
</li>
Run Code Online (Sandbox Code Playgroud)
这是编写包装link_to的自己的帮助程序的好例子.在您的application_helper.rb中,您可以编写一个方法active_link_to,该方法使用与link_to + current_page相同的参数,然后像上面一样调用link_to.
根据 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"
Run Code Online (Sandbox Code Playgroud)
你可以这样使用它
<%= link_to 'Home', root_path, class: class_names('nav-link', { active: current_page?(root_path) }) %>
Run Code Online (Sandbox Code Playgroud)
它会产生这样的html
<a class="nav-link active" href="/">Home</a>
Run Code Online (Sandbox Code Playgroud)
医生在这里