[英]Rails. Extend link_to helper
如何擴展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>
等等
您可以通過兩種方式設置多個html類。 可以是用空格分隔的字符串,也可以是數組。
def my_cool_link_to(name = nil, options = nil, html_options = nil, &block)
html_options[:class] ||= [] # ensure it's not nil
if html_options[:class].is_a? Array
html_options[:class] << 'your-class' # append as element to array
else
html_options[:class] << ' your-class' # append with leading space to string
end
link_to(name, options, html_options, block) # call original link_to
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.