Symfony2 - 检查文件是否存在 [英] Symfony2 - checking if file exists

查看:28
本文介绍了Symfony2 - 检查文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Twig 模板中有一个循环,它返回多个值.最重要的是 - 我的条目的 ID.当我不使用任何框架或模板引擎时,我只是在循环中使用了 file_exists().现在,我似乎无法在 Twig 中找到方法.

I have a loop in Twig template, which returns multiple values. Most important - an ID of my entry. When I didn't use any framework nor template engine, I used simply file_exists() within the loop. Now, I can't seem to find a way to do it in Twig.

当我在标题中显示用户头像时,我在控制器中使用 file_exists(),但我这样做是因为我没有循环.

When I display user's avatar in header, I use file_exists() in controller, but I do it because I don't have a loop.

我在 Twig 中尝试了 defined,但它对我没有帮助.有什么想法吗?

I tried defined in Twig, but it doesn't help me. Any ideas?

推荐答案

如果你想检查一个不是 twig 模板的文件的存在(这样定义不能工作),创建一个 TwigExtension 服务并添加 file_exists() 函数到树枝:

If you want want to check the existence of a file which is not a twig template (so defined can't work), create a TwigExtension service and add file_exists() function to twig:

src/AppBundle/Twig/Extension/TwigExtension.php

<?php

namespace AppBundle\Twig\Extension;

class FileExtension extends \Twig_Extension
{

    /**
     * Return the functions registered as twig extensions
     * 
     * @return array
     */
    public function getFunctions()
    {
        return array(
            new Twig_SimpleFunction('file_exists', 'file_exists'),
        );
    }

    public function getName()
    {
        return 'app_file';
    }
}
?>

注册您的服务:

src/AppBundle/Resources/config/services.yml

# ...

parameters:

    app.file.twig.extension.class: AppBundle\Twig\Extension\FileExtension

services:

    app.file.twig.extension:
        class: %app.file.twig.extension.class%
        tags:
            - { name: twig.extension }

就是这样,现在您可以在树枝模板中使用 file_exists() ;)

That's it, now you are able to use file_exists() inside a twig template ;)

一些模板.twig:

{% if file_exists('/home/sybio/www/website/picture.jpg') %}
    The picture exists !
{% else %}
    Nope, Chuck testa !
{% endif %}

编辑以回答您的评论:

要使用 file_exists(),您需要指定文件的绝对路径,因此您需要 web 目录绝对路径,这样做可以访问您的 twig 模板中的 webpathapp/config/config.yml:

To use file_exists(), you need to specify the absolute path of the file, so you need the web directory absolute path, to do this give access to the webpath in your twig templates app/config/config.yml:

# ...

twig:
    globals:
        web_path: %web_path%

parameters:
    web_path: %kernel.root_dir%/../web

现在您可以在树枝模板中获取文件的完整物理路径:

Now you can get the full physical path to the file inside a twig template:

{# Display: /home/sybio/www/website/web/img/games/3.jpg #}
{{ web_path~asset('img/games/'~item.getGame.id~'.jpg') }}

这样你就可以检查文件是否存在:

So you'll be able to check if the file exists:

{% if file_exists(web_path~asset('img/games/'~item.getGame.id~'.jpg')) %}

这篇关于Symfony2 - 检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆