Tomek Buszewski Tomek Buszewski - 1 year ago 1056
Twig Question

Symfony2 - checking if file exists

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

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
in controller, but I do it because I don't have a loop.

I tried
in Twig, but it doesn't help me. Any ideas?

Answer Source

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:



namespace AppBundle\Twig\Extension;

class FileExtension extends \Twig_Extension

     * Return the functions registered as twig extensions
     * @return array
    public function getFunctions()
        return array(
            new Twig_SimpleFunction('file_exists', 'file_exists'),

    public function getName()
        return 'app_file';

Register your service:


# ...


    app.file.twig.extension.class: AppBundle\Twig\Extension\FileExtension


        class: %app.file.twig.extension.class%
            - { name: twig.extension }

That's it, now you are able to use file_exists() inside a twig template ;)

Some template.twig:

{% if file_exists('/home/sybio/www/website/picture.jpg') %}
    The picture exists !
{% else %}
    Nope, Chuck testa !
{% endif %}

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:

# ...

        web_path: %web_path%

    web_path: %kernel.root_dir%/../web

Now you can get the full physical path to the file inside a twig template:

{# Display: /home/sybio/www/website/web/img/games/3.jpg #}
{{ web_path~asset('img/games/''.jpg') }}

So you'll be able to check if the file exists:

{% if file_exists(web_path~asset('img/games/''.jpg')) %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download