如何在Symfony中替换未找到的图像

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.

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") }}'"/>

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>