Rails从Helper模块返回多个content_tags

Rya*_*ing 4 html ruby module ruby-on-rails helper

我写了以下帮助:

def section_to_html (block)
      case block[0].downcase
      when "paragraph"
        block.shift
        block.each do |value|
          return content_tag(:p, value)
        end
      end
  end
Run Code Online (Sandbox Code Playgroud)

它目前正在解析这些数组.

["paragraph", "This is the first paragraph."]
["paragraph", "This is the second.", "And here's an extra paragraph."]
Run Code Online (Sandbox Code Playgroud)

它返回:

<p>This is the first paragraph.</p>
<p>This is the second.</p>
Run Code Online (Sandbox Code Playgroud)

有没有办法累积content_tag?所以它返回:

<p>This is the first paragraph.</p>
<p>This is the second.</p>
<p>And here's an extra paragraph.</p>
Run Code Online (Sandbox Code Playgroud)

我现在唯一的解决方案是使用部分解决方案.但是,一旦我开始添加更多案例条件,这将变得非常混乱.

Mik*_*e T 6

由于您想返回一系列标签而不必将它们嵌套在另一个标签中,并且您正在处理来自数组的内容,因此可以这样做:

paragraphs = %w(a b c d e) # some dummy paragraphs
tags = html_escape('') # initialize an html safe string we can append to
paragraphs.each { |paragraph| tags << content_tag(:p, paragraph) }
tags # is now an html safe string containing your paragraphs in p tags
Run Code Online (Sandbox Code Playgroud)

content_tag返回ActiveSupport::SafeBuffer(继承自String)的实例。调用html_escape空字符串将使该字符串成为 的实例ActiveSupport::SafeBuffer,因此当您将content_tag调用的输出附加到它时,您将获得 html 安全字符串中的所有标签。

(我今天在尝试解决同样的问题时发现了这个问题。我的解决方案对于原始问题来说已经晚了好几年,但希望能帮助其他人!)