I have a loop in Twig template, which returns multiple values. Most important – an ID of my entry. When I didn’t use any framework nor template engine, I used simply file_exists() within the loop. Now, I can’t seem to find a way to do it in Twig.
When I display user’s avatar in header, I use file_exists() in controller, but I do it because I don’t have a loop.
I tried defined in Twig, but it doesn’t help me. Any ideas?
If you want want to check the existence of a file which is not a twig template (so defined can’t work), create a TwigExtension service and add file_exists() function to twig:
src/AppBundle/Twig/Extension/TwigExtension.php
Register your service:
src/AppBundle/Resources/config/services.yml
That’s it, now you are able to use file_exists() inside a twig template 😉
Some template.twig:
EDIT to answer your comment:
To use file_exists(), you need to specify the absolute path of the file, so you need the web directory absolute path, to do this give access to the webpath in your twig templates
app/config/config.yml:
Now you can get the full physical path to the file inside a twig template:
So you’ll be able to check if the file exists: