为rails中的所有活动链接添加“活动”类?
基本上,我有很多代码看起来像这样:
link_to t('.profile'), business_path(@business), class: '#{'active' if current_page? business_path(@business)}'
这不是很干。
我想知道是否有人知道修改link_to帮助程序本身的好方法,以自动将“活动”类添加到当前页面的所有链接。
如果有帮助,我愿意使用HAML或SLIM。
这是编写包装link_to的自己的帮助程序的好例子。 在你的application_helper.rb中,你可以编写一个方法active_link_to
,它接受与link_to + current_page相同的参数,然后就像你在上面那样调用link_to。
我在视图助手current_page?
使用build编写了简单的帮助方法current_page?
何时可以在html_options
哈希中指定自定义class
名。
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 %> # Main <%= active_link_to "Main", root_path, class: "bordered" %> # Main <%= active_link_to "Main", root_path, class: "bordered", active: "disabled" %> # Main
这是一个解决的问题,只需使用active_link_to gem。 您的示例简化为:
= active_link_to t('.profile'), business_path(@business)
我面临同样的要求,这是我的解决方案。
在ApplicationHelper
创建方法
def active_class(link_path) current_page?(link_path) ? "active" : "" end
在你的观点内:
<%= link_to 'HOME', root_path %>
这是我使用的助手。 我添加了一个可选的“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
使用link_to_unless_current
,然后在CSS中显示活动链接。