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

我的梦境 提交于 2019-11-30 08:57:50

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

To ensure the operation, you can use:

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

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!