Check if file exists in Symfony2
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php namespace Sybio\Bundle\CoreBundle\Twig; use \Twig_Filter_Function; use \Twig_Filter_Method; class TwigExtension extends \Twig_Extension { /** * Return the functions registered as twig extensions * * @return array */ public function getFunctions() { return array( 'file_exists' => new \Twig_Function_Function('file_exists'), ); } public function getName() { return 'twig_extension'; } } ?> |
The next step will be to register your service in “src/Sybio/Bundle/CoreBundle/Resources/config/config.yml” like this:
1 2 3 4 5 |
services: sybio.twig_extension: class: Sybio\Bundle\CoreBundle\Twig\TwigExtension tags: - { name: twig.extension } |
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:
1 2 3 4 5 |
{% if file_exists('/some/path/to/picture.jpg') %} The file exists ! {% else %} The file is not found ! {% endif %} |
This is another demonstration for this function:
1 |
{% if file_exists(web_path~asset('images/users/'~ user.idUser ~'.png')) %} |
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!