Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 687
THpubs Avatar asked Dec 29 '12 11:12

THpubs


3 Answers

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 %>
like image 133
Khaled Avatar answered Nov 14 '22 14:11

Khaled


To ensure the operation, you can use:

@images = Dir.glob("#{Rails.root}/app/assets/images/camisas/*.jpg")
like image 36
Daniel Avatar answered Nov 14 '22 15:11

Daniel


Works for me and displays images:

Dir.glob('app/assets/images/slide/*').map do |path| 
  image_tag "slide/#{ File.basename(path) }"
end.reduce(&:+)

You want to get rid of the full path with File#basename so it works with precompiled assets afaik. You also don't need to specify .jpg because its an images folder, and could have .png's.

like image 1
AJcodez Avatar answered Nov 14 '22 15:11

AJcodez