Codeigniter2 用のLayout library を作ったよ
Codeigniter でもレイアウトの共有機能を使いたいなぁ、ということで作ったよ。
application/libraries/Layout.php
<?php /** * Layout library * * @author localdisk<info@localdisk.org> */ class Layout { /** * ci * * @var Codeigniter */ private $_ci; /** * data * * @var array */ private $_data = array(); /** * layout * * @var string */ private $_layout; /** * constructor * * @param string $layout */ public function __construct($layout = 'layout/main') { $this->_ci = get_instance(); $this->_layout = $layout; } /** * setLayout * * @param string $layout */ public function setLayout($layout) { $this->_layout = $layout; return $this; } /** * write * * @param string $key * @param string $value */ public function write($key, $value) { $this->_data[$key] = $value; return $this; } /** * render * * @param boolean $ret * @return string */ public function render($ret = FALSE) { if ($ret === TRUE) { $out = $this->_ci->load->view($this->_layout, $this->_data, $ret); return $out; } $this->_ci->load->view($this->_layout, $this->_data); } }
application/views/layout/main.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja"> <head> <title><?= $title ?></title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/> </head> <body> <div id="header"> <h1>hoge</h1> </div> <div id="body"> <?= $content ?> </div> <div id="footer"> <address>footer</address> </div> </body> </html>
application/controllers/Home.php
<?php class Home extends CI_Controller { public function __construct() { parent::__construct(); } public function index() { $this->load->library('layout'); $this->layout->write('title', 'テストタイトル')->write('content', '本文')->render(); } }
自分で言うのもなんですが、結構便利だと思います。使ってみたい方はご自由にー。