简体   繁体   中英

Symfony 5 how paste image to twig from no public directory

The images are located in non public folder. And I want return the image to twig.

I tried use BinaryFileResponse

    $actualSignature = $this->getParameter('dir_signatures') .'/'.$actualSignature->getName();
    $binaryFileSignature = new BinaryFileResponse($actualSignature);

and return it to twig

return $this->render('security/profile.html.twig',['form' => $form->createView(),'signature' => $binaryFileSignature]);

And in twig

<img src="{{ signature.file }}"/>

You can make a controller action that returns just an image like this:

/**
 * @Route("image/{imagePath}", name="show_image")
 */
public function showimageAction(string $imagePath): BinaryFileResponse
{
    $response = new BinaryFileResponse(
        $this->getParameter('kernel.project_dir')
        . '/'
        . $this->getParameter('dir_signatures') // related to project root dir
        . '/'
        . $imagePath
    );
    $response->setContentDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT
    );
    return $response;
}

Then pass to your template just image name to get:

return $this->render('security/profile.html.twig',[
    'form' => $form->createView(),
    'signature' => $actualSignature->getName()
]);

And in template:

<img src="{{ path('show_image', {imagePath: signature}) }}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM