mbm
mbm

Reputation: 1922

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 words, 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.

Upvotes: 0

Views: 416

Answers (2)

Tim Stephenson
Tim Stephenson

Reputation: 830

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

Upvotes: 1

polarblau
polarblau

Reputation: 17734

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.

Upvotes: 0

Related Questions