Format-Agnostic Image Tag Helper

Hey all,

I’m looking for a way to embed an <img> without having to specify its format extension. Has anyone written a helper for this?

I can accomplish it in Slim but it’s clunky and hard to reuse:

- data.people.each do |person|

  - imagePath = "images/#{person.name.parameterize}"
  - imageFormats = [".jpg", ".jpeg", ".png"]
  - imageFound = false

  - imageFormats.each do |imageFormat|
    - image = "#{imagePath}#{imageFormat}"
     - if sitemap.find_resource_by_path("#{image}")
       img src="#{image}"
       - imageFound = true
       - break

  - if imageFound == false
    img src="/images/no-photo.jpg"

I’d rather write something like

= smart_image_tag '#{person.name.parameterize}'

Any help is appreciated!

In your config.rb:

helpers do

  def smart_image_tag(image_name)
    image_path = image_path(image_name)
    image_formats = [".jpg", ".jpeg", ".png"]
    image_found = false
    image_output = nil

    image_formats.each do | image_format |
      if sitemap.find_resource_by_path(image_path + image_format)
        image_output = image_tag image_name + image_format
        image_found = true
        break
      end
      
      if image_found == false
        image_output = image_tag 'no-photo.jpg'
      end
    end
    return image_output
  end

end

Now you can simply replace your Slim:

- people.each do |person|
  = smart_image_tag person.name.parameterize
1 Like

Thank you so much, Tom. This worked wonderfully.

Cheers :raised_hands: