Symfony 3 – Serve image within twig extension

I want to serve several images wich are not avaibles in public folder (web) using php for example path/to/myphp/script.php?image=imagereference&some=parameter

To improve performances and not using this approach I made a twig extension to do that.

<?php

#src/MyBundle/Service/DisplayImage.php

namespace MyBundleService;

#https://symfony.com/blog/new-in-symfony-2-4-the-request-stack
use SymfonyComponentHttpFoundationRequestStack;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentHttpFoundationResponse;

class DisplayImage
{
    private $entityManagerInterface;
    private $requestStack;

    public function __construct(EntityManagerInterface $entityManagerInterface, RequestStack $requestStack)
    {
        $this->entityManagerInterface = $entityManagerInterface;
        $this->requestStack = $requestStack;
    }

    public function show(int $ref)
    {
        $photoPath = __DIR__ ."/../photoFolder/".$ref.".jpg";
        $file = file_get_contents($photoPath);

        $response = new Response();
        $response->headers->set('Content-Type', 'image/jpeg');
        $response->setContent($file);
        return $response;
    }
}

And into my twig template

{# src/MyBundle/Ressources/views/DisplayImage.html.twig #}

{% for ref in refs %}
  <img src="{{ show(ref) }}"/>
{% endfor %}

But it doesn’t work because the response returned is not a valid src path.

So my question is how generate URL that target my twig extension ?

Something like path/to/twigExtension.php?ref=ref calls show(ref)

Maybe it’s not the good way to achieve that

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *