Symfony2 - 检查文件是否存在

Tom*_*ski 13 symfony twig

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

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

我试过definedTwig,但它对我没有帮助.有任何想法吗?

Syb*_*bio 31

如果您想要检查是否存在不是twig模板的文件(如此定义无法工作),请创建TwigExtension服务并将file_exists()函数添加到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';
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

注册您的服务:

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 }
Run Code Online (Sandbox Code Playgroud)

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

一些template.twig:

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

编辑回答你的评论:

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

# ...

twig:
    globals:
        web_path: %web_path%

parameters:
    web_path: %kernel.root_dir%/../web
Run Code Online (Sandbox Code Playgroud)

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

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

因此,您将能够检查文件是否存在:

{% if file_exists(web_path~asset('img/games/'~item.getGame.id~'.jpg')) %}
Run Code Online (Sandbox Code Playgroud)


Ric*_*oor 11

我创建了一个Twig函数,它是我在这个主题上找到的答案的扩展.我的asset_if函数有两个参数:第一个是资产显示的路径.如果第一个资产不存在,则第二个参数是后备资产.

创建扩展文件:

SRC/Showdates/FrontendBundle /嫩枝/分机/ ConditionalAssetExtension.php:

<?php

namespace Showdates\FrontendBundle\Twig\Extension;

use Symfony\Component\DependencyInjection\ContainerInterface;

class ConditionalAssetExtension extends \Twig_Extension
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * Returns a list of functions to add to the existing list.
     *
     * @return array An array of functions
     */
    public function getFunctions()
    {
        return array(
            'asset_if' => new \Twig_Function_Method($this, 'asset_if'),
        );
    }

    /**
     * Get the path to an asset. If it does not exist, return the path to the
     * fallback path.
     * 
     * @param string $path the path to the asset to display
     * @param string $fallbackPath the path to the asset to return in case asset $path does not exist
     * @return string path
     */
    public function asset_if($path, $fallbackPath)
    {
        // Define the path to look for
        $pathToCheck = realpath($this->container->get('kernel')->getRootDir() . '/../web/') . '/' . $path;

        // If the path does not exist, return the fallback image
        if (!file_exists($pathToCheck))
        {
            return $this->container->get('templating.helper.assets')->getUrl($fallbackPath);
        }

        // Return the real image
        return $this->container->get('templating.helper.assets')->getUrl($path);
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
       return 'asset_if';
    }
}
Run Code Online (Sandbox Code Playgroud)

注册您的服务(app/config/config.ymlsrc/App/YourBundle/Resources/services.yml):

services:
    showdates.twig.asset_if_extension:
        class: Showdates\FrontendBundle\Twig\Extension\ConditionalAssetExtension
        arguments: ['@service_container']
        tags:
          - { name: twig.extension }
Run Code Online (Sandbox Code Playgroud)

现在在您的模板中使用它,如下所示:

<img src="{{ asset_if('some/path/avatar_' ~ app.user.id, 'assets/default_avatar.png') }}" />
Run Code Online (Sandbox Code Playgroud)