1

如何扩展 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>

等等

4

1 回答 1

0

有两种方法可以设置多个 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
于 2014-12-13T22:47:49.617 回答