Twig 检查文件是否存在

Twig check if file exists

您好,我正在使用 slim 框架和 twig,这是我在 php 中的当前代码:

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

现在我想将 if 语句放入我的模板文件中。我如何在我的 Twig 模板中使用 file_exists 函数来检查文件是否存在?

您可以创建自己的函数或 test 并将参数传递给 PHP 函数。

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

然后在您的模板中:

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

不幸的是存在在英语中听起来很奇怪。也许函数会更有意义。

如果您确实需要在模板端进行验证,那么创建一个自定义函数就可以了。但 Twig 并不意味着以这种方式使用。

您可以只在验证 php 一侧并将标志传递给您的模板:

PHP

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

树枝

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

免责声明:我不知道使用 Slim(这里是 Symfony2 的人)渲染树枝模板的确切方法,但这是相同的逻辑。

对于那些使用 Symfony 和 Liip Image vich_uploader,并且想要检查数据库存储文件是否存在(例如在图像列表/图库中)的人,这是我的解决方案:

{% set filePath = vich_uploader_asset(image, 'imageFile') %}
{% if filePath is not null %}
   ....
{% endif %}