4

Normally you would include images with

<img src="{{ asset('location') }}"/>

But if the image doesn't exist, a 404 is thrown and a broken image is shown. How to show another image instead of a broken one? Is there a way to do it in twig?

I'm also using SonataMediaBundle which shows images like so:

{% path media, 'small' %}

Figured there would be a way inside the bundle to check if the image exists, but it doesn't.

George Irimiciuc
  • 4,573
  • 8
  • 44
  • 88

2 Answers2

3

Try using onerror if you don't want to check the file's existence before hand

<img src="{{ path("image.svg") }}" onerror="this.src='{{path("image.png") }}'"/>
David
  • 33,444
  • 11
  • 80
  • 118
2

You can do this with rewrite. Create a .htaccess file in project directory. Add the following lines.

RewriteEngine On
<FilesMatch "\.(jpe?g|png|gif)$">
    ErrorDocument 404 "/img/default-image.gif"
</FilesMatch>

EDIT

You can use DirectoryMatch for matching directories. Also you can nest FilesMatch inside it.

<DirectoryMatch "^/www/xyz/"> <FilesMatch "\.(jpe?g|png|gif)$"> ErrorDocument 404 "/img/default-image.gif" </FilesMatch> </DirectoryMatch>

Harikrishnan
  • 9,688
  • 11
  • 84
  • 127