我已经覆盖了 link_to 以期望 class_if 参数,请查看:
def link_to(options = {}, html_options = {})
if html_options.is_a?(Hash) && html_options.key?(:class_if)
html_options[:class] <<
(" #{html_options[:class_if][1].strip}") if html_options[:class_if][0]
html_options.delete :class_if
end
super(options, html_options)
end
及用法:
<%= link_to(my_path, class: "class1", class_if: [true_or_false?, 'class2']) %>
我刚刚重写了一种方法,但一个很好的重构是在此处重写所有描述的签名:http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
更新
另一种解决方案是:
module ApplicationHelper
def active_link_to(name = nil, options = nil, html_options = nil, &block)
html_options ||= { class: '' }
html_options[:class].concat('is-active') if options.match(controller_name)
link_to(name, options, html_options, &block)
end
end
及用法:
<%= active_link_to(my_path, 'My path') %>
这样,即使是自定义路由,例如“my_path/help”、“my_path/two”,我也能获得“活动状态”。