Created
July 11, 2017 16:34
-
-
Save tai-sho/950444189ffb3b7a4034a10aaf34e140 to your computer and use it in GitHub Desktop.
jQueryLazyloadを扱うHelper #cakephp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* jquery.lazyloadの制御を行うHelper | |
*/ | |
class LazyLoadHelper extends AppHelper { | |
/** | |
* 使用するヘルパーの宣言 | |
* @var array | |
*/ | |
public $helpers = array('Html'); | |
/** | |
* Lazyload読込中に表示する画像 | |
* @var string | |
*/ | |
public $placeholder = '/path/to/spinner.gif'; | |
/** | |
* jQuerylazyLoadのパス | |
* @var string | |
*/ | |
public $lazyLoadScriptPath = '/path/to/jquery.lazyload.min'; | |
/** | |
* lazyLoad用クラス | |
* @var string | |
*/ | |
public $lazyLoadClass = 'lazy'; | |
/** | |
* lazyLoadに引き渡すオプション | |
* @var array | |
*/ | |
public $lazyloadOptions = array('effect' => 'fadeIn', 'event' => 'scroll'); | |
/** | |
* レンダー前処理 | |
* @param string $viewFile Viewファイルパス | |
* @see Helper::beforeLayput() | |
*/ | |
public function beforeLayout($viewFile) { | |
parent::beforeLayout($viewFile); | |
$this->Html->script($this->lazyLoadScriptPath, array('inline' => false)); | |
$options = json_encode($this->lazyloadOptions); | |
$this->Html->scriptBlock("$(function() { $('.{$this->lazyLoadClass}').lazyload({$options}); });", array('inline' => false)); | |
} | |
/** | |
* lazyLoad用imgタグ出力 | |
* $optionはHtmlHelper::imageに直接引き渡されます | |
* @param string $path 画像パス | |
* @param array $options 画像オプション | |
* @param string $placeholder 読み込み中に表示する画像パス | |
*/ | |
public function image($path = null, $options = array(), $placeholder = null) { | |
$options['data-original'] = $path; | |
$path = isset($placeholder) ? $placeholder : $this->placeholder; | |
if(isset($options['class']) && is_array($options['class'])) { | |
$options['class'][] = $this->lazyLoadClass; | |
} elseif(isset($options['class'])) { | |
$options['class'] = (string)$options['class']. ' '. $this->lazyLoadClass; | |
} else { | |
$options['class'] = $this->lazyLoadClass; | |
} | |
return $this->Html->image($path, $options); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment