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")
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';" />
A pure Ruby on Rails solution:
<%= image_tag 'devices/my-device.png' rescue image_tag 'devices/unknow-device.png' %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With