[eluser]Fra_T[/eluser]
To include header, footer and/or sidebar in every view is a really boring practice.
To define a single layout with all the common parts once and then to define the singles action-specific views with just the code that changes sounds better :-)
To do it in CI I've used this simple approach.
A) I define a "layout" with all the common parts:
view/site_layout.php:
Code:
<html>
<head>
<title>Welcome to CodeIgniter</title>
<style type="text/css">
/*...*/
</style>
</head>
<body>
<?php echo $action?>
<p><br />Page rendered in {elapsed_time} seconds</p>
</body>
</html>
b) I define an "action" with the action-specific code.
views/welcome_message.php:
Code:
<h1>Welcome to CodeIgniter!</h1>
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>system/application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>system/application/controllers/welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
c) Then I load/set the layout in the constructor (or in any other place in the Controller):
controllers/welcome.php:
Code:
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
$this->load->layout('site_layout');
}
function index()
{
$this->load->view('welcome_message');
}
}
d) And finally here we have the library that make the things happen:
libraries/my_loader.php:
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Loader extends CI_Loader {
var $_layout;
function layout($layout) {
$this->_layout = $layout;
return $this;
}
function view($view, $vars = array(), $return = FALSE)
{
if (isset($this->_layout)) {
$this->_ci_cached_vars['action'] = $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => true));
return $this->_ci_load(array('_ci_view' => $this->_layout, '_ci_vars' => array(), '_ci_return' => $return));
} else {
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
}
}
With this library you can load your views in the classic CI way, but you can also define a layout for your views.
This is my first contribute to CI. What do you think about it?