【问题标题】:Twig check if file existsTwig 检查文件是否存在
【发布时间】:2015-10-05 06:41:33
【问题描述】:

您好,我使用的是 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 函数来检查文件是否存在?

【问题讨论】:

标签: php twig file-exists


【解决方案1】:

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

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

然后在你的模板中:

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

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

【讨论】:

  • 我应该把创建的函数放在哪里?
  • 很难理解但会尝试:D
【解决方案2】:

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

您可以只制作 valitadion 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 的人)渲染树枝模板的确切方法,但这是相同的逻辑。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      相关资源
      最近更新 更多