【问题标题】:content_tag do with multiple parts using concatcontent_tag 使用 concat 处理多个部分
【发布时间】:2012-08-24 22:32:13
【问题描述】:

我正在使用 Rails 3。我正在尝试在帮助程序中执行此操作:

def headers collection
  collection.each do |col|
     content_tag(:th, col.short_name)
  end
end

如您所见,这个想法是通过 content_tag 为集合中的每个元素生成一个<th> 标签。这不起作用,因为 HTML 是由 Rails 提供的安全的,这使得它不能作为 HTML 工作。

如果我把它改成这样:

def headers collection
  collection.each do |col|
    concat (content_tag(:th, col.short_name))
  end
end

这样效果更好。我在 HTML 中得到了正确的标记,但在此之前我得到了所有标记 HTML 安全。所以我觉得我很接近了。

我知道还有其他方法可以做到这一点,但我想尝试以正确优雅的方式做到这一点。我错过了什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 helpers


    【解决方案1】:

    您可以使用 inject 并以 html_safe 空字符串开头。

    def headers collection
      collection.inject("".html_safe) do |content, col|
        content + (content_tag(:th, col.short_name))
      end
    end
    

    【讨论】:

      【解决方案2】:

      聚会迟到了,但我今天遇到了这个问题并用safe_join解决了它,所以:

      def headers_collection 
        safe_join(collection.map { |item| content_tag(:th, item.short_name) })
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-26
        • 2021-02-20
        • 1970-01-01
        • 2020-03-14
        • 2016-01-29
        • 1970-01-01
        相关资源
        最近更新 更多