Check if file exists in Symfony2

→ Are you a new visitor? Please visit the page guidance for new visitors ←

Check if file exists in Symfony2

If you want want to check if file exists in Symfony2 and which is not a twig template, you have to create a Twig Extension service and add a file_exists() function or whatever you want to call it in twig.

This tutorial is more specific to the issue we have at hand, meaning to check if file exists in Symfony2, however this tutorial can be used for any type of php function or any other type of method you can think of and you require it to have in twig template. Basically you create Twig Extensions that allows you to extend functionality further in your twig template.

Creating the Twig Extensions

We will work with a specific namespace for this tutorial which is Sybio\Bundle\CoreBundle and this will be in your own project the exact namespace of your bundle. You can find more information on creating a bundle here.

So, let’s proceed by adding in “src/Sybio/Bundle/CoreBundle/Twig/TwigExtension.php” the following code:

The next step will be to register your service in “src/Sybio/Bundle/CoreBundle/Resources/config/config.yml” like this:

The same piece of code can be added in your “src/Sybio/Bundle/CoreBundle/Resources/config/services.yml“.

This is pretty much all the configuration you need! You cand now access this new function in the twig template like this:

This is another demonstration for this function:

This is how you can create a custom file_exists function in Symfony2, and have access to it from a twig template. You can check for existence of files, assets or other stuff very easy with this method.

See you again in our next tutorial!

Request an article ←