2014-06-16 36 views
1

有没有一种方法来检查文件是否存在于Twig中,以便在新创建的文章中上传的图像?Symfony2 - 检查一个文件是否存在于Twig

我有我的后期设置的方式是,如果图片没有上传,树枝模板将显示一个空框,图像应该在哪里的比例,但它是一个空白的框,看起来很尴尬。

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

图片代码:(这是我想隐藏,如果没有图像的存在是为了摆脱空箱子的密码)

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

回答

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."); 
    } 

,但我宁愿在你的img标签使用javascripz像

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

更新:

图像标签有一个onError的处理程序时,没有找到src属性的图像触发。因此,而不是使用这个简单的语法内嵌你可以做同样的,如:

伪jQuery代码:

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

你的意思是像我只是做? –

相关问题