Search code examples
symfonytwigliipimaginebundle

LiipImagineBundle default image


Is there a clean solution for displaying a default image in case a file does not exist in the database? I don't need to check if the file exists in the filesystem for example with file_exists.

Please take a look at the following code:

{% if user.file %}
    <img src="{{ vich_uploader_asset(user, 'file')|imagine_filter('thumbnail') }}" />
{% else %}
    <img src="url/default_image.jpg" />
{% endif %}

Check has to be done every time, for every image in the template which obscures the code.

Is there any way of extending imagine_filter or any other solution (a service maybe)?

Update: I consider this thread to be closed. Also, I've reported a LiipImagineBundle bug #749.

Just for a future reference, to show a default image in case it does not exist:

content.twig.html

<img src="{{ vich_uploader_asset(user, 'File')|default_image|imagine_filter('thumbnail') }}" />

parameters.yml

parameters:
    default_image_path: /uploads/nophoto.png

config.yml

twig:
    globals:
        default_image_path: "%default_image_path%"

services.yml

services:
    app.twig.app_extension:
        public:    false
        class:     AppBundle\Twig\AppExtension
        arguments: ['@markdown', '%app_locales%', '@service_container']
        tags:
            - { name: twig.extension }

AppBundle/Twig/AppExtension.php

namespace AppBundle\Twig;

use AppBundle\Utils\Markdown;
use Symfony\Component\Intl\Intl;
use Symfony\Component\DependencyInjection\ContainerInterface;

class AppExtension extends \Twig_Extension
{
    /**
     * @var Markdown
     */
    private $parser;

    /** @var ContainerInterface */
    protected $container;    

    /**
     * @var array
     */
    private $locales;

    public function __construct(Markdown $parser, $locales, ContainerInterface $container)
    {
        $this->parser = $parser;
        $this->locales = $locales;
        $this->container = $container;
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('default_image', array($this, 'getDefaultImage') ),
        );
    }


    public function getDefaultImage(string $path = null)
    {
        $defaultImagePath = $this->container->getParameter('default_image_path');
        return $path ? $path : $defaultImagePath;
    }   

Solution

  • I have no idea if VichUploaderBundle handles well a user with no file, but have you tried creating your own Twig filter? Something that would look like:

    <img src="{{ vich_uploader_asset(user, 'file')|default_image|imagine_filter('thumbnail') }}" />
    

    Then in your custom Twig extension:

    public function getDefaultImage(string $path)
    {
        return $path ? $path : 'url/default_image.jpg';
    }