Rails How To List all Images in a Folder using the

2019-02-06 15:29发布

问题:

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

回答1:

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 %>


回答2:

To ensure the operation, you can use:

@images = Dir.glob("#{Rails.root}/app/assets/images/camisas/*.jpg")


回答3:

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.



回答4:

files = Dir.glob('app/assets/images/slide/*')
files.each do |file|
  puts file
end


回答5:

From the documentation, image_tag returns an html image tag for the source. It cannot show all images at once. You should make a custom helper to read and walk through your directory.