开发者

Image tag generation in Rails

If working in Rails, what's the best way to define a helper function that generates many image tags? This function would then be called from a .erb file, producing a view.

In other word开发者_运维知识库s, something like

def build_view; image_tag("seg-433.png", :alt => "Shit don't work", :class => "round"); end

but that returns many tags.

Feel free to suggest a more idiomatic approach, I just started riding the Rails train, like, yesterday.


If you have an image model you could create a helper like this:

/app/helpers/my_controller_helper.rb

module MyControllerHelper
  def bunch_of_image_tags
    images = []
    Image.all.each do |image|
      images << image_tag(image.path, :alt => image.alt, :class => image.class)
    end
    images.join("<br/>")
  end
end

You could also get a list of files from the file system, but I'm not sure what you would use for the alt tag in that case. Also look at paper_clip - https://github.com/thoughtbot/paperclip


You could render a collection of partials which contains everything you need for your image tag.

render :partial => "image", :collection => @images

the partial "image" being the one containing the image tag. More at api.rubyonrails.org.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜