codeigniterのヘッダー、フッターはhookでなくloadで対応する

CodeIgniter footer header 未分類

small__364815092
photo credit: mrlerone via photopin cc

 

codeigniterでheaderとfooterを設定するときに、hookで対応する記事をよく見かけるが、

タイトルやデスクリプションなどURL毎に設定したい場合、やっかいだったりする。

view関数を呼び出したときにheaderとfooterを呼ぶ

$this->load->view();を呼び出したときにその前後にフッターとヘッダーを入れれば
各々コントローラで呼び出した時にタイトルやデスクリプションが設定できます。

view関数はloadオブジェクトつまりCI_Loaderクラスで定義しており、
それと application/core/my_loader.php を作成してCI_Loader クラスを親クラスとしてカスタマイズすれば対応可能です。

class MY_Loader extends CI_Loader {

	function __construct(){
		parent::__construct();
		$this->header_path = APPPATH . "views/header.php";
		$this->footer_path = APPPATH . "views/footer.php";
	}

	public function set_header($view)
	{
		$this->header_path = APPPATH . "views/".$view.".php";
	}

	public function set_footer($view)
	{
		$this->footer_path = APPPATH . "views/".$view.".php";
	}

	public function view($view, $vars = array(), $return = FALSE)
	{
		$ci =& get_instance();
		$class = $ci->router->fetch_class(); // Get class
		$action = $ci->router->fetch_method(); // Get action

		// 共通headerを読み込まない処理をいれる
		if(strpos($action, 'ajax') !== FALSE  || $class == "static") {
		} else{
			$header =  $this->_ci_load(array('_ci_path' => $this->header_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
		}

		// ボディ
		$body =  $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));

		// 共通footerを読み込まない処理をいれる
		if(strpos($action, 'ajax') !== FALSE  || $class == "static") {
		} else{
			$footer =  $this->_ci_load(array('_ci_path' => $this->footer_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
		}

		if($return) {
			return $body;
		}
	}
}
?>

関連記事

コメント

この記事へのコメントはありません。

カテゴリー

お問い合わせはコチラ!