Rails 助手渲染数组,而不是 html

Rails Helper renders array, not html

如果我调用 render_slider_items(["a.png", "b.png", "c.png"]),我的网页显示数组 ["a.png", "b.png", "c.png"],而不是 html。

module ApplicationHelper
 def render_slider_items(filenames)
    filenames.each do |filename|
      content_tag(:div, class: "col-md-3") do 
        tag("img", src: "assets/#{filename}")
      end
    end
  end
end

什么会导致这种情况?

更新-解决方案-

      def render_slider_items(filenames)
        filenames.collect do |filename|
          content_tag(:div, class: "col-md-3") do 
            tag("img", src: "assets/#{filename}")
          end
        end
      end.join().html_safe

我猜你是这样称呼它的

#some_file.html.erb
<%= render_slider_items(["a.png", "b.png", "c.png"]) %>

如果是这种情况,那么发生这种情况的原因是因为 .each 方法 returns the array 它正在迭代。你最好这样做:

module ApplicationHelper
 def render_slider_items(filenames)
    filenames.collect do |filename|
      content_tag(:div, class: "col-md-3") do 
        tag("img", src: "assets/#{filename}")
      end
    end
  end.join.html_safe
end