CodeIgniter2 #04 Layout レイアウトライブラリ
標準では Layout 機能がないのでここからもらってくる。
// file /application/libraries/Layout.php
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Layout
{
var $obj;
var $layout;
function Layout($layout = "layout_main")
{
$this->obj =& get_instance();
$this->layout = $layout;
}
function setLayout($layout)
{
$this->layout = $layout;
}
function view($view, $data=null, $return=false)
{
$loadedData = array();
$loadedData['content_for_layout'] = $this->obj->load->view($view,$data,true);
if($return)
{
$output = $this->obj->load->view($this->layout, $loadedData, true);
return $output;
}
else
{
$this->obj->load->view($this->layout, $loadedData, false);
}
}
}
?>
使い方はこんな感じ。
// 最初にライブラリの読み込み
$this->load->library('layout', 'layout_main');
// もしいつも使うのであれば、application/config.php にて以下の設定を行う
$autoload['libraries'] = array('layout');
// ビューの出力
$data->title_for_layout='ページタイトル';
$this->layout->view('/shop/view_cart', $data);
// layout ファイル /application/views/layout_main.php
<html>
<head>
<title><?=$title_for_layout?></title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<link rel="stylesheet" href="/css/main.css" type="text/css" />
</head>
<body>
<div id="pagewidth" >
<div id="header" ><img src="/images/header.jpg" width="700" height="200"></div>
<div id="wrapper" class="clearfix" >
<div id="twocols" class="clearfix">
<?php echo $content_for_layout?>
</div>
</div>
<div id="footer" > Footer >/div>
</div>
</body>
</html>