Tomek Buszewski Tomek Buszewski - 4 months ago 264
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

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?

Answer

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

<?php

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:

src/AppBundle/Resources/config/services.yml

# ...

parameters:

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

services:

    app.file.twig.extension:
        class: %app.file.twig.extension.class%
        tags:
            - { 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:

# ...

twig:
    globals:
        web_path: %web_path%

parameters:
    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/'~item.getGame.id~'.jpg') }}

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

{% if file_exists(web_path~asset('img/games/'~item.getGame.id~'.jpg')) %}