简体   繁体   中英

How to load images in twig from root directory folder in Symfony 2?

I'm new in Symfony and my problem is simple, I just can't load images from a certain directory and display it to twig. I have this upload folder located in the root directory of my Symfony project (outside of web folder). This folder is just a link to other VM through Linux file system and which has the original upload folder. I've tried to check if it exists using php's

file_exists('/var/www/html/<projname>/upload/somefolder/image.png');

and it shows that the image exists but when I'm trying to display the images in twig, it always shows 404 error not found and the image is not displaying. I've already did this:

<img src="/var/www/html/<projname>/upload/somefolder/image.png" />

and

<img src="/upload/somefolder/image.png" />

How does symfony handle this situation?

If you want to get the path of your root directory you can try below code. Here is a best example provided for file uploading.

$this->get('kernel')->getRootDir() . '/../web' . $this->getRequest()->getBasePath();

Might be this can also help you.

I would suggest using asset() (see https://symfony.com/doc/current/templating.html#templating-assets ), but this also requires you to put your folder under projects web/ -directory so it could be accessed by symfony and webserver (in combination).

Since you're using a linux, it's simple as that:

cd /var/www/html/<projname>/
ln -s upload web/upload

Now you can simply reference to your assets like:

{{ asset('upload/somefolder/image.png') }}

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