Template Library for CodeIgniter, Simple, Fast and Easy!

If you have not noticed, I just got started on CodeIgniter. I was really disappointed today when I noticed the lack of a template system in CodeIngiter to skin my little application. They say

The Template Parser Class is not a full-blown template parsing solution. We’ve kept it very lean on purpose in order to maintain maximum performance.

Lucky for me, I got a little help here, the library is great and works well for the latest version of CI too best of all its small and does not modify the CI code in anyway. It just uses the already available code to skin the application. Sleak!

I made a couple of modifications in the original library, here are my modifications

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 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);
	}
	
	// load a default template 'template.php'
	function view($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);
	}
}

/* End of file Template.php */
/* Location: ./system/application/libraries/Template.php */

So now I use it like

$this->template->view('my_view', $view_data);

instead of

$this->template->load('template', 'my_view', $view_data);

Hope it helps somebody.

2 thoughts on “Template Library for CodeIgniter, Simple, Fast and Easy!

  • Eric

    While I realize this blog post is 3 years old, I found it and figured a slight modification I made to the above process might be worth someone else’s time as well. Hell, there may even be a blog post after this one stating this exact solution. Either way, instead of defining a second function with identical code to maintain (save the hard coded template), define a wrapper function that defines ‘template’ for you such as:

    function view($view_data = array(), $return = FALSE)
    {
    $this->load(‘template’, $view_data, $return);
    }

    Just put that function in your Template.php file and you’ve saved yourself some code duplication. I tested both methods (with CodeIgniter 2.1.0 and PHP 5.3.10) and they seem to function identically.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.