Skip to content

Instantly share code, notes, and snippets.

@ikuwow
Created September 19, 2015 14:30
Show Gist options
  • Save ikuwow/9ebe9626233ab0671941 to your computer and use it in GitHub Desktop.
Save ikuwow/9ebe9626233ab0671941 to your computer and use it in GitHub Desktop.
CakePHP2系で画像がなかったらnoimage画像を出す ref: http://qiita.com/ikuwow/items/29f950a7d7924ba92035
class AppController extends Controller {
public $helpers = array(
'Html' => array('className' => 'CustomHtml')
);
(略)
}
<?php
App::uses('AppHelper', 'View/Helper');
App::import('Helper', 'Html');
class CustomHtmlHelper extends HtmlHelper {
public function image($path, $options = array()) { // override
// 画像のパスをパース(HtmlHelper::image()と同様)
$realPath = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
// 同ホストの画像の場合のみ
if (!preg_match('|(https?:)?//|',$realPath) && !file_exists(WWW_ROOT.$realPath)) {
$path = 'noimage.jpg';
}
return parent::image($path, $options);
}
}
<div>
<?= $this->Html->image('myIcon.jpg')?>
</div>
<div>
<?= $this->Html->image('//localhost:8383/img/myIcon.jpg')?>
</div>
<div>
<?= $this->Html->image('http://localhost:8383/img/myIcon.jpg')?>
</div>
<div>
<?= $this->Html->image('https://localhost:8383/img/myIcon.jpg')?>
</div>
<div>
<?= $this->Html->image('noimage.jpg')?>
</div>
<div>
<?= $this->Html->image('anotherIcon.jpg')?>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment