ruby-on-railsrubyruby-on-rails-3.2

Rails How To List all Images in a Folder using the image_tag?


Im trying to take all the images in the 'app/assets/images/slide' folder and put them withing tags (in order). So, it will look like this :

<img src="1.jpg" >
<img src="2.jpg" >
<img src="3.jpg" >

How can I achive this? (Im using Rails 3.2.9)

Here's the code I tried (thanks to Khaled). But it outputs a plain text list of all image paths. I need the images to show :

@images = Dir.glob("app/assets/images/slide/*.jpg")

@images.each do |image|
    image_tag image.gsub("app/assets/images/", "")
end

Solution

  • In your controller action, get all images paths.

    @images = Dir.glob("app/assets/images/slide/*.jpg")
    

    Then in your view (assuming haml)

    - @images.each do |image|
       = image_tag "slide/#{image.split('/').last}"
    

    Assuming erb

     <% @images.each do |image| %>
       <%= image_tag "slide/#{image.split('/').last}" %>
     <% end %>