【发布时间】:2016-11-01 09:47:32
【问题描述】:
基于this 帖子
我正在尝试检查远程图像是否存在(正确加载),如果存在,则显示它,否则显示默认图像。我已经做了一个树枝扩展并更正了代码,但它总是返回 false,尽管我明确知道图像存在。我的树枝模板代码如下:
{% if file_exists(author.image) %} //always get false here so the default image is loaded
<img src="{{ author.image }}" alt="{{ author.name }}">//loads an image correctly if outside condition
{% else %}
<img src="/var/www/web/img/no_image.png" alt="no_image">
{% endif %}
感谢任何帮助。谢谢。
UPD我的twig函数如下:
<?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';
}
}
【问题讨论】:
-
你的 twig 函数的代码是什么?
-
author.image是图片的绝对路径吗?可能不会 -
author.image 是一个远程图像,类似于scontent.cdninstagram.com/t51.2885-15/s150x150/e35/…
-
您的更新中实际的 file_exists 函数代码在哪里?假设您的模型 getter 如果没有图像则返回 false,为什么不直接做
if not author.image -
那么你不需要
file_exists。您可以获取资源的标头,并检查状态是否为 404。如果是 404,则图片不存在。