【问题标题】:Rails. Extend link_to helper导轨。扩展 link_to 助手
【发布时间】: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


【解决方案1】:

有两种方法可以设置多个 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

【讨论】:

  • 我不认为这回答了原来的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多