Most Simple Template Library for CodeIgniter

Warning: this tutorial and library are out of date. Prefer the last version.

Example

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('mainTemplate', 'about', $data);

It loads the view about.php into the template mainTemplate.php.

Installation

  • Put Template.php in “system/application/libraries”
  • Autoload it: in config/autoload.php: $autoload['libraries'] = array('template');

How to use it

Create a template file

views/mainTemplate.php

<html>
 
<head>
<meta name="author" content="Who am I?" />
</head>
 
<body>
 
<div id="header">
Cooking by yourself is worth!
</div>
 
<div id="contents">
<?php require_once($template_contents.'.php'); ?>
</div>
 
<div id="footer">
Copyright maestric.com
</div>
 
</body>
</html>

The magic comes with this line:

<?php require_once($template_contents.'.php'); ?>

which indicates where your view code will be inserted.

Create a view

views/about.php

<h1>Template Library for Code Igniter.</h1>
 
<p>Ladies and gentlemen, yes, that's unbelievable!</p>

Load the view into the template

In a controller's method:

$this->template->load('mainTemplate', 'about');

How it works

The source code is incredibly short and straightforward: libraries/Template.php

class Template {
        function load($template = '', $view = '' , $vars = array(), $return = FALSE)
        {
                $vars['template_contents'] = APPPATH . 'views/' . $view;
                $this->CI =& get_instance();
                return $this->CI->load->view($template, $vars, $return);
        }
}

Advanced use 1: more slots in your template

Life is not so simple. You'll probably need more slots in your template, for example for the HTML header's title. To keep the code readable, I write one method for each template: libraries/Template.php

class Template {
        function load($template = '', $view = '' , $vars = array(), $return = FALSE)
        {
                $this->CI =& get_instance();
                $vars['template_contents'] = $view;
                if ($template == "mainTemplate")
                        return $this->loadMainTemplate($view, $vars, $return);
                else 
                        return $this->CI->load->view($template, $vars, $return);
        }
 
 
        function loadMainTemplate($view, $vars = array(), $return = FALSE)
        {
                if( ! isset($vars['head_title']))
                        $vars['head_title'] = "Default Title";
 
                return $this->CI->load->view("mainTemplate", $vars, $return);
        }
}

In the HTML header of your template file:

<title><?= $head_title ?></title>

Then you can define this title directly in your controllers the normal way:

$data['head_title'] = 'Photos';
$this->template->load('mainTemplate', 'about', $data);

Advanced use 2: highlight the current menu item

Usually the menu is a fixed part of your pages and should be in your template file. However, you may want to highlight the item corresponding to the current page, so your visitor knows where he is.

Update the template library

Add to Template.php:

var $currentMenuItem = "";
 
function setCurrentMenuItem($str)
{
    $this->currentMenuItem = $str;
}

Add to Template.php in loadMainTemplate():

$vars['menuItems'] = array('Home', 'Photos', 'Software', 'About', 'Contact');
$vars['currentMenuItem'] = $this->currentMenuItem;

Your new Template class:

class Template {
 
 
        function load($template = '', $view = '' , $vars = array(), $return = FALSE)
        {
                $this->CI =& get_instance();
                $vars['template_contents'] = $view;
                if ($template == "mainTemplate")
                        return $this->loadMainTemplate($view, $vars, $return);
                else
                        return $this->CI->load->view($template, $vars, $return);
        }
 
 
        // --------------------------------------------------------------------
        // Main Template
 
        var $currentMenuItem = "";
 
        function setCurrentMenuItem($str)
        {
                $this->currentMenuItem = $str;
        }
 
        function loadMainTemplate($view, $vars = array(), $return = FALSE)
        {
                $vars['menuItems'] = array('Home', 'Photos', 'Software', 'About', 'Contact');
                $vars['currentMenuItem'] = $this->currentMenuItem;
 
                return $this->CI->load->view("mainTemplate", $vars, $return);
        }
 
        // --------------------------------------------------------------------
 
}

Update your template

You can now use these variables in mainTemplate.php:

<html>
<body>
 
<div class="menu">
<?php
foreach($menuItems  as $i => $menuItem):
	if ($menuItem == $currentMenuItem)
       		$anchorAttribbutes = array('class' => 'selected');
	else
       		$anchorAttribbutes = array();
	echo anchor($menuItem, $menuItem, $anchorAttribbutes);
	if (isset($menuItems[$i + 1]))
		echo " | ";
endforeach;
?>
</div>
 
<div id="contents">
<?php require_once($template_contents.'.php'); ?>
</div>
 
</body>
</html>

To be able to use the anchor function, you can autoload the url helper in config/autoload.php.

Update your controllers

To choose the current menu item, you can add some lines like that in your controller:

$this->template->setCurrentMenuItem('Photos');

This line can be put in a method, or directly in the controller if all controller's methods share the same menu item. You just need now to define the corresponding CSS style (#menu .selected).

 

Feedback

any suggestions on how to get this template class to work with parser?
todd g
January 30, 2008
#1
In the template class, replace:
return $this->CI->load->view($template, $vars, $return);
by:
$this->CI->load->library('parser');
return $this->CI->parser->parse("mainTemplate", $vars, $return);
Maestric
February 1, 2008
#2
I like to keep my views in sub-directories but when I was calling them like I was used to in CI, I was getting a could not include error on the page load. ie. $this->template->load('template/mainTemplate', 'user/profile', $data); I had to add: $view = APPPATH."views/".$view; to the Template library file to fix this problem. In case anybody else was having this issue....
jram
February 4, 2008
#3
This is perhaps the best templating solution I've seen for Codeigniter. Using it...Kudos!
Thumper
February 25, 2008
#4
$this->template->load->('mainTemplate', 'about', $data); should be $this->template->load('mainTemplate', 'about', $data); :)
Ruben Müller
February 25, 2008
#5
Thank you Ruben, that's fixed! :)
Maestric
February 25, 2008
#6
Excellent!! Will this work with kohanaphp 2.0 too?
Tony
March 14, 2008
#7
The same idea works with Kohana 2 :) Here's the Template Library rewritten for Kohanna:
class Template_Core {

        function load($template = '', $view = '' , $vars = array(), $return = FALSE)
        {
                $wholeView = new View($template, $vars);
                $wholeView->template_contents = $view;
                $wholeView->render(TRUE);
        }

}
The corresponding code in the controller is the same:
$this->load->library('template');
$this->template->load('mainTemplate', 'about');
You can of course autoload the library and add a data array as parameter to the load method.
Maestric
March 14, 2008
#8
Great stuff!! Thanks, I will give it a try
Tony
March 14, 2008
#9
jram: you said that you added: $view = APPPATH."views/".$view; to the template library to fix that problem... im having a bit of trouble implementing that technique - could you show me where I need to add it?
Danny
April 9, 2008
#10
Danny: I integrated jram's fix :)
Maestric
April 11, 2008
#11
Hi Maestric, I was looking for a common library something similar to this for my website. Excellent work! This will help me finish my website sooner. Thanks again.
Kiri Kurukkal
April 13, 2008
#12
Hi - this is great - thanks so much for sharing. Fantastic!
woopsicle
June 28, 2008
#13
Exactly what I need! Many thanks, simple, lightweight and really really fast!
Fabio
September 15, 2008
#14
If I keep all the controllers in one file, the menu doesn't link properly, so it means I need to create a controller and a view file for every page?
Someguy
October 13, 2008
#15
When I use it, CI doesn't rewrite the short tags (i.e. "<?='Hello World'?>")
Moshe
October 20, 2008
#16
In your php.ini set short_open_tag = On
Jérôme Jaglale
October 20, 2008
#17
I keep getting the error msg "unable to load the class: template". Any ideas will be appreciated.
Al
October 23, 2008
#18
For what it's worth I've just had success with this template class and Elliot Haughin's ci_inferno ( http://www.haughin.com/2008/08/18/introducing-inferno-codeigniter-libraries/).
Al
October 24, 2008
#19
Al's problem was that he was using CI 1.4.1. With this version, create in system/init a file called init_template.php:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

if ( ! class_exists('Template'))
{
     require_once(APPPATH.'libraries/Template'.EXT);
}

$obj =& get_instance();
$obj->myclass = new Template();
$obj->ci_is_loaded[] = 'template';

?>
Jérôme Jagale
October 25, 2008
#20

December 29, 2008
#21
okey... tanks coy...
salam kenal..
aq rofi from indonesia...
AyeA!
rofiant
May 26, 2010
#22
test
test
December 27, 2010
#23