[eluser]thurting[/eluser]
I wrote a hook that pretty much mimics RoR behavior.
In your config/hooks.php add:
Code:
$hook['display_override'][] = array('class' => 'Yield',
'function' => 'doYield',
'filename' => 'Yield.php',
'filepath' => 'hooks'
);
Create a file named application/hooks/Yield.php:
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Yield :: HOOKS
*
* Adds layout support :: Similar to RoR <%= yield =>
* '{yield}' will be replaced with all output generated by the controller/view.
*/
class Yield
{
function doYield()
{
global $OUT;
$CI =& get_instance();
$output = $CI->output->get_output();
if (isset($CI->layout))
{
if (!preg_match('/(.+).php$/', $CI->layout))
{
$CI->layout .= '.php';
}
$requested = BASEPATH . 'application/views/layouts/' . $CI->layout;
$default = BASEPATH . 'application/views/layouts/default.php';
if (file_exists($requested))
{
$layout = $CI->load->file($requested, true);
$view = str_replace("{yield}", $output, $layout);
}
else
{
$layout = $CI->load->file($default, true);
$view = str_replace("{yield}", $output, $layout);
}
}
else
{
$view = $output;
}
$OUT->_display($view);
}
}
?>
Create a folder in views named layouts. In this folder create a file name default.php ... this will serve as your default layout if none is specified in a controller. To add another layout, just create a file in views/layouts and define the variable in your controller. For example if you had a file named views/layouts/example.php and a controller named controllers/example.php:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Example.php</title>
</head>
<body>
{yield}
</body>
</html>
Code:
<?php
class Example extends Controller
{
public $layout = 'example';
public function __construct()
{
parent::Controller();
}
public function index()
{
$this->load->view('index_view');
}
}
The string {yield} in your layout file will be replaced with the output generated by the view file loaded from the controller. Not as easy as with Rails, but the behavior is there for the most part. BTW, if the variable $layout is not defined in your controller, CI will do its default behavior... so you can use layouts in some scenarios and not in others.