【问题标题】:Rails Return multiple content_tags from Helper moduleRails 从 Helper 模块返回多个 content_tags
【发布时间】:2013-03-21 12:32:15
【问题描述】:

我编写了以下帮助程序:

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>

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

【问题讨论】:

    标签: html ruby-on-rails ruby module helper


    【解决方案1】:

    【讨论】:

    • 是的,我在看那个,但我很难弄清楚如何让它适应我的情况。
    【解决方案2】:

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

    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 安全字符串中的所有标签。

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

    【讨论】:

    • 谢谢!你的回答对我有帮助!
    猜你喜欢
    • 2010-09-11
    • 2011-06-07
    • 2013-01-17
    • 2016-03-07
    • 2017-08-05
    • 2014-04-23
    • 2014-12-23
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多