if else 在 cakePHP 中不显示默认图像

if else in cakePHP not displaying default image

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

因此,由于某种原因,如果数据库中有一个条目,则 $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;

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

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

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

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