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

三世轮回 提交于 2019-11-29 13:04:31

问题


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.



来源:https://stackoverflow.com/questions/14081109/rails-how-to-list-all-images-in-a-folder-using-the-image-tag

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