【问题标题】:Rails content_tag on ul with an iteration带有迭代的 ul 上的 Rails content_tag
【发布时间】:2019-01-02 19:40:44
【问题描述】:

我有一个文本字段,用户输入了我要转换为列表项的数据。所以他们可能会在文本区域输入:

Apple
Tomato
Wrench

所以我有以下工作:

 <% regional_services = @region.services.split("\n") %>
  <ul>
   <%regional_services.each do |services| %>
    <li><%=services%></li>
   <%end%>
  </ul>

它使用类似的东西正确输出

  • 苹果
  • 番茄
  • 扳手

但我正试图让它在助手中工作,因为它在视图中很难看。

所以我有以下内容:

def other_service
  if @region.services.present?
    something = @region.services.split("\r\n")
    content_tag(:ul) do
      content_tag(:li, something.each {|alpha| alpha })
    end
  else
    content_tag(:p, 'Here is text')
  end
end

它最终输出如下:

  • [“苹果”、“番茄”、“扳手”]

所以看起来它没有在列表项上应用迭代,所以我尝试了以下方法:

def other_service
 if @region.services.present?
   regional_service = @region.services.split("\n")
   content_tag(:ul) do
     regional_service.each do |service|
       content_tag(:li, service)
     end
   end
 else
   content_tag(:p, 'Here is text')
 end
end

没有错误,但实际上没有在实际包含项目的页面上显示任何内容。那么如何通过迭代来做 content_tag ul 呢?

【问题讨论】:

  • 使用concat:...each do |service| concat content_tag(...); end
  • Welp...这就是解决方案

标签: ruby-on-rails


【解决方案1】:

each 返回数组,因此content_tag :ul 的块将接收数组本身作为内部 HTML。这显然不是您想要的。

为了将 HTML 添加到输出缓冲区,您可以使用 concat:

content_tag :ul do
  regional_service.each do |service|
    concat content_tag(:li, service)
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多