【发布时间】:2014-12-13 21:18:05
【问题描述】:
如何扩展 Rails 的 link_to 助手以添加特定的类而不破坏 link_to 标准功能。 我想要这样的自定义助手:
module MyModule
module MyHelper
def my_cool_link_to(body, url_options, html_options)
# here add 'myclass' to existing classes in html_options
# ?? html_options[:class] || =
link_to body, url_options, html_options
end
end
end
我想保留 link_to 的所有功能:
=my_cool_link_to 'Link title', product_path(@product)
# <a href=".." class="myclass">Link title</a>
=my_cool_link_to 'Link title', product_path(@product), :class=>'btn'
# <a href=".." class="btn myclass">Link title</a>
=my_cool_link_to 'Link title', product_path(@product), :class=>'btn', 'data-id'=>'123'
# <a href=".." data-id="123" class="btn myclass">Link title</a>
等等
【问题讨论】:
-
如果您这样做只是为了添加类,那么创建一个帮助方法来添加您的类并使用标准的link_to 可能会更明智。
link_to name, link, class: new_method(old_class) -
这个想法是创建一个助手,将必要的选项(不仅是 :class,还有其他选项)添加到用户指定的选项中。我也想这样写:=my_cool_link_to 'Link title', product_path(@product),不指定任何类,但它应该向链接添加必要的类。
标签: ruby-on-rails link-to view-helpers link-to-function