Twig check if file exists

Hello I am using slim framework and twig and here is my current code in php:

$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}

      

Now I want to put an if statement in a template file. How can I use a function file_exists

in my branch template so that I can check if the file exists?

+3


source to share


2 answers


Creating a custom function is just fine if you really need to do template-side validation. But Twig is not meant to be used that way.

You can just make valpadion php side and pass the flag to your template:

PHP

$filename = '/path/to/foo.txt';
$file_exists = file_exists($filename);
// ...
$app->render(
    'yourTemplate',
    array( 'file_exists' => $file_exists )
);

      



TWIG

{% if file_exists %}
    do stuff
{% endif %}

      


Disclaimer: I don't know the exact way to render the branch template using Slim (Symfony2 guy here), but that's the same logic.

+3


source


You can create your own function or test and just pass the arguments to the PHP function.

$test = new Twig_SimpleTest('ondisk', function ($file) {
    return file_exists($file);
});

      

And then in your template:



{% if filename is ondisk %}
    blah
{% endif %}

      

Unfortunately, it sounds strange in English. Perhaps the function would make more sense.

+8


source







All Articles