【问题标题】:if else in cakePHP not displaying default image如果 cakePHP 中的 else 不显示默认图像
【发布时间】:2015-03-11 23:17:23
【问题描述】:

当存储在数据库中的图像的文件路径条目为空时,我正在尝试在 cakePHP 中显示默认图像。我发现下面的代码正在发生,如果数据库条目为空,则显示默认图像,但如果数据库中有条目,它也会显示。

因此,由于某种原因,如果 DB 中有条目 $image 没有被显示。感谢您的帮助。

保罗

<?php

$image = $this->Html->image(
        $news['News']['imgPath'],
        array('title' => $news['News']['alt_tag'], 'class' => 'left'),
        array('escape' => false));                 

    $default_image = "<img src=\"/FBCW_new2/files/uploads/default.jpg\" class=\"left\" alt=\"default image\"/>";

    if(file_exists("$image")) $filename = $image;

    else $filename = $default_image;

    echo $filename;
  ?>

分辨率: 由于$image是html字符串,所以我添加了一个变量,首先检查文件路径是否为空,然后通过它设置$filename。

        $photo = $news['News']['imgPath'];
        $image = $this->Html->image(
                      $news['News']['imgPath'],
                      array('title' => $news['News']['alt_tag'], 'class' => 'left'),
                      array('escape' => false));                 

      $default_image = "<img src=\"/FBCW_new2/files/uploads/default.jpg\" class=\"left\" alt=\"default image\"/>";

       if(!empty($photo)) $filename = $image;

       else $filename = $default_image;

       echo $filename;

【问题讨论】:

    标签: php image cakephp file-exists


    【解决方案1】:

    您正在检查$image 是否是一个有效的文件路径,但$image 包含一个HTML 字符串;因此,file_exists 几乎总是会返回false。您要检查文件路径是否有效:

    if(file_exists(APP . WEBROOT_DIR . '/' . $news['News']['imgPath'])){
         // ...
    }
    

    注意:根据您存储这些图像的位置(以及存储它们的文件路径的方式),您可能需要使用 APP 常量(和其他)来检查正确的绝对文件路径。

    您可能想要创建一个帮手来为您进行这样的图像替换,请参阅Helpers - CakePHP Cookbook 2.0

    【讨论】:

    • 感谢 Jacob,我已将代码更改为以下内容,但现在不显示默认图像。 $image = $this->Html->image( $news['News']['imgPath'], array('title' => $news['News']['alt_tag'], 'class' => 'left'), array('escape' => false)); $default_image = ""; if(file_exists(APP . WEBROOT_DIR . '/' . $news['News']['imgPath'])) $filename = $image;否则 $filename = $default_image;回声$文件名;
    • @Paul 显示的是什么而不是默认图像?您检查过生成的 HTML 源吗?你能在条件句周围加括号吗?
    • 对于数据库中没有文件路径的记录,视图源中显示的是:。 $default_image 的格式应该不同吗?
    • 我已经解决了这个问题。通过指出 $image 是一个帮助的 html 字符串。我已经添加了上面的分辨率。
    猜你喜欢
    • 2012-07-23
    • 1970-01-01
    • 2018-03-11
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2015-08-10
    • 1970-01-01
    相关资源
    最近更新 更多