rubyruby-on-rails-4helperpartialscontent-for

Rails Helper renders array, not html


If I call render_slider_items(["a.png", "b.png", "c.png"]) my webpage shows the array ["a.png", "b.png", "c.png"], not the 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

What would cause this?

UPDATE - Solution-

      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

Solution

  • I'm guessing you're calling this like this

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

    If that's the case the reason this is happening to you is because the .each method returns the array it's iterating over. You'd be better off doing something like this:

    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