I can't vouch that this is the best approach, but I create a base controller like this:
class MY_Controller extends CI_Controller {
public $title = '';
// The template will use this to include default.css by default
public $styles = array('default');
function _output($content)
{
// Load the base template with output content available as $content
$data['content'] = &$content;
$this->load->view('base', $data);
}
}
The view called 'base' is a template (a view that includes other views):
<?php echo doctype(); ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php $this->load->view('meta'); ?>
</head>
<body>
<div id="wrapper">
<?php $this->load->view('header'); ?>
<div id="content">
<?php echo $content; ?>
</div>
<?php $this->load->view('footer'); ?>
</div>
</body>
</html>
What this achieves is that every controller wraps its output in the base template, and that views have valid HTML instead of opening tags in one view and closing in another. If I'd like a specific controller to use a different or no template, I could just override the magic _output()
method.
An actual controller would look like this:
class Home extends MY_Controller {
// Override the title
public $title = 'Home';
function __construct()
{
// Append a stylesheet (home.css) to the defaults
$this->styles[] = 'home';
}
function index()
{
// The output of this view will be wrapped in the base template
$this->load->view('home');
}
}
Then I could use its properties in my views like this (this is the 'meta' view that populates the <head>
element):
echo "<title>{$this->title}</title>";
foreach ($this->styles as $url)
echo link_tag("styles/$url.css");
I like my approach because it respects the DRY principle and the header, footer and other elements get included just once in the code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…