7

Hello so 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 the if statement in my template file. How can I use the file_exists function in my twig template so I can check whether a file exists?

wobsoriano
  • 12,348
  • 24
  • 92
  • 162

3 Answers3

14

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 is exists sounds weird in English. Perhaps a function would make more sense.

Anonymous
  • 11,740
  • 3
  • 40
  • 50
8

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

You can just make the valitadion php side and pass a 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 a twig template using Slim (Symfony2 guy here), but it's same logic.

viarnes
  • 2,018
  • 2
  • 19
  • 31
0

For those who use Symfony with Liip Image vich_uploader, and want to check, if a DB stored files exists or not (for example on image list / gallery), this is my solution:

{% set filePath = vich_uploader_asset(image, 'imageFile') %}
{% if filePath is not null %}
   ....
{% endif %}
Harkály Gergő
  • 733
  • 8
  • 18