Note: Updated on November 1, 2008. Previous version is still available.
How you usually load a view:
$this->load->view('about', $data);
How you load a view into a template with this library:
$this->template->load('template', 'about', $data);
That loads the view about.php into template.php.
Template.php into system/application/librariesconfig/autoload.php:$autoload['libraries'] = array('template');
views/template.php
<html> <body> <div id="contents"><?= $contents ?></div> <div id="footer">Copyright 2008</div> </body> </html>
$contents is where your view will be inserted.
In your controller:
$this->template->load('template', 'about');
The view is loaded into a variable which is given to the template.
var $template_data = array(); function set($name, $value) { $this->template_data[$name] = $value; } function load($template = '', $view = '' , $view_data = array(), $return = FALSE) { $this->CI =& get_instance(); $this->set('contents', $this->CI->load->view($view, $view_data, TRUE)); return $this->CI->load->view($template, $this->template_data, $return); }
Example: you want to set the page title.
Add an HTML header to views/template.php
<head>
<title><?= $title ?></title>
</head>
Set the title in your controller before loading the view:
$this->template->set('title', 'About me');
Navigation is usually part of the template. However, it's a good practice to highlight the item corresponding to the current page, so your visitors know where they are.
Add to libraries/Template.php under $this->set('contents...:
$this->set('nav_list', array('Home', 'Photos', 'About', 'Contact'));
Add in views/template.php:
<ul class="navigation"> <?php foreach($nav_list as $i => $nav_item): ?> <li class="<?= ($nav == $nav_item ? 'selected' : '')?>"> <?= anchor($nav_item, $nav_item) ?> </li> <?php endforeach ?> </ul>
To be able to use the anchor function, autoload the url helper in config/autoload.php:
$autoload['helper'] = array('url');
Add:
$this->template->set('nav', 'About');
Notes:
#navigation .selected).
To easily deal with multiple templates, define new load methods in libraries/Template.php instead of modifying the existing one. Advanced use 2 with a custom method:
function load_main($view = '', $view_data = array(), $return = FALSE) { $this->set('nav_list', array('Home', 'Photos', 'About', 'Contact')); $this->load('template', $view, $view_data, $return); }
Corresponding code in your controller:
$this->template->set('nav', 'About'); $this->template->set('title', 'About me'); $this->template->load_main('about');