如果image_tag无法从网址加载图片,我想渲染默认图片:
因此,如果image_tag无法从网址加载图片:
<%= image_tag 'https://something.com/image.jpg' %>
然后渲染默认值:
<%= image_tag image_url("default.png")
答案 0 :(得分:6)
onerror
标记中的img
属性。<%= image_tag 'https://something.com/image.jpg',
src: 'Image Not Found',
onerror: 'this.error=null;this.src="default.png"' %>
这将生成生成的HTML:
<img src='https://something.com/image.jpg'
alt="Image not found"
onerror="this.onerror=null;this.src='default.png';" />
答案 1 :(得分:1)
纯Ruby on Rails解决方案:
<%= image_tag 'devices/my-device.png' rescue image_tag 'devices/unknow-device.png' %>