【问题标题】:symfony2 twig check if a remote image existssymfony2 twig 检查远程图像是否存在
【发布时间】: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,则图片不存在。

标签: php symfony twig


【解决方案1】:

嗯,您创建的 Twig-Extension 使用 PHP-Function file_exists,它仅适用于本地文件。
为了使它适用于远程文件,您需要像这样更改它(未经测试):

<?php

namespace AppBundle\Twig\Extension;

class FileExtension extends \Twig_Extension
{
    /**
     * Return the functions registered as twig extensions
     *
     * @return array
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('remote_file_exists', [$this, 'remoteFileExists']),
        ];
    }

    /**
     * @param string $url
     *
     * @return bool
     */
    public function remoteFileExists($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $status === 200 ? true : false;
    }

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

?>

现在您应该可以使用 Twig-Function remote_file_exists 来检查您的图像是否存在。

【讨论】:

  • 谢谢,我试试看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 2010-11-24
  • 1970-01-01
  • 2016-07-09
  • 1970-01-01
  • 2015-10-05
  • 2012-02-14
相关资源
最近更新 更多