Symfony2 twig add new function file_exists

An important function is missing on twig : file_exists.

I will show you here how to define a new function for twig.

On your namespace/bundle, add a Twig/Extension directory and create your class file :


namespace Adin\ArlogisBundle\Twig\Extension;

class FileExistsExtension extends \twig_Extension
         *Return the function registered as twig extension
         *@return array
        public function getFunctions()
                return array(
                        'file_exists' => new \Twig_Function_Function('file_exists'),

        public function getName()
                return 'adin_file_exists';

You then have to register your service, add a in your /Adin/ArlogisBundle/Ressources/config/services.xml file

<?xml version="1.0" ?>

<container xmlns=""
       <service id="adin.twig.tripix_extension" class="Adin\ArlogisBundle\Twig\Extension\FileExistsExtension">
        <tag name="twig.extension" />

It’s ready, you can use it on your twig template

{% if file_exists('/var/www/image.jpg') %}
    File exists
{% else %}
    File not exists
{% endif %}

Be carefull, you need to specify the absolute path of the file. You can create a twig global variable root_path.

# Twig Configuration
        root_path: %kernel.root_dir%/../web

Then on twig template

{% if file_exists({{root_path}}'/var/www/image.jpg') %}
    File exists
{% else %}
    File not exists
{% endif %}

Leave a Reply