簡體   English   中英

Rails從Helper模塊返回多個content_tags

[英]Rails Return multiple content_tags from Helper module

我寫了以下幫助:

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

它目前正在解析這些數組。

["paragraph", "This is the first paragraph."]
["paragraph", "This is the second.", "And here's an extra paragraph."]

它返回:

<p>This is the first paragraph.</p>
<p>This is the second.</p>

有沒有辦法累積content_tag? 所以它返回:

<p>This is the first paragraph.</p>
<p>This is the second.</p>
<p>And here's an extra paragraph.</p>

我現在唯一的解決方案是使用部分解決方案。 但是,一旦我開始添加更多案例條件,這將變得非常混亂。

既然你想要返回一系列標簽而不必將它們嵌套在另一個標簽中,並且你正在處理來自數組的內容,那么這就可以了:

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

content_tag返回ActiveSupport::SafeBuffer (繼承自String )。 在空字符串上調用html_escape將使該字符串成為ActiveSupport::SafeBuffer ,因此當您將content_tag調用的輸出附加到它時,您將獲得html安全字符串中的所有標記。

(我今天在嘗試解決同樣的問題時發現了這個問題。我的解決方案對於原始問題來說已經太晚了,但希望能幫助其他人!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM