【问题标题】:Symfony2 - Checking if a file exists in TwigSymfony2 - 检查 Twig 中是否存在文件
【发布时间】:2014-06-16 23:15:57
【问题描述】:

有没有办法检查 Twig 中是否存在在新创建的帖子中上传的图像的文件?

我的帖子设置方式是,如果未上传图片,Twig 模板将显示一个空框,其中包含图片应有的比例,但这是一个很难看的空框。

问题,是否有一个特定的命令可以与 if 语句一起使用来检查文件是否存在,如果存在,则显示图像代码,如果不显示图像代码。

图片代码:(这是我想隐藏的代码,如果不存在图像以摆脱空框)

<div class="entry-thumbnail">
    <img width="230" height="172" src="{{ asset(['images/', post.image]|join) }}" class="" alt=""/>
</div>

【问题讨论】:

    标签: image symfony twig


    【解决方案1】:

    您可以编写一个树枝扩展并使用如下代码:

    use Symfony\Component\Filesystem\Filesystem;
    use Symfony\Component\Filesystem\Exception\IOException;
    use Symfony\Component\Finder\Finder;
    
    
        $this->fs=new Filesystem();
    
        if (!$this->fs->exists($directory)) {
            $this->logger->info("there is no ".$directory." ...");
        } else {
            $this->logger->info("Directory ".$directory."  already exists.");
        }
    

    但我宁愿像使用 javascripz 一样

    在您的 img 标签中:

    <img ... onError="this.src='imagefound.gif';" />
    

    更新:

    图片标签有一个onError-Handler,当src属性中的图片找不到时触发。因此,您可以这样做,而不是使用这种简单的内联语法:

    伪jquery代码:

    $(document).on('error','img',function(){
        $(this).attr("src","../path/to/placeholerImage.png");
    });
    

    【讨论】:

    • 你的意思是像我刚才那样?
    猜你喜欢
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2012-12-23
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多