content_tag使用concat处理多个部分

时间:2012-08-24 22:32:14

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

我正在使用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安全。所以我觉得我很接近。

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

晚会,但我今天遇到了这个并用safe_join解决了,所以:

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