Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Load default image if image_tag cannot load image from url

I want to render a default image if image_tag cannot load an image from a url:

So if image_tag cannot load image from url:

<%= image_tag 'https://something.com/image.jpg' %>

then render default:

<%= image_tag image_url("default.png")
like image 713
gr8scott06 Avatar asked Oct 05 '16 22:10

gr8scott06


2 Answers

Use the onerror attribute in the img tag.

<%= image_tag 'https://something.com/image.jpg', 
      src: 'Image Not Found', 
      onerror: 'this.error=null;this.src="default.png"' %>

This will generate the resulting HTML:

<img src='https://something.com/image.jpg' 
  alt="Image not found" 
  onerror="this.onerror=null;this.src='default.png';" />
like image 150
Fakhir Shad Avatar answered Nov 19 '22 04:11

Fakhir Shad


A pure Ruby on Rails solution:

<%= image_tag 'devices/my-device.png' rescue image_tag 'devices/unknow-device.png' %>
like image 38
ubugnu Avatar answered Nov 19 '22 04:11

ubugnu