My Blog

Code Igniter Template Tutorial

7.07.2008 | Develop, How-To

I have recently been using Code Igniter and I will say it is an awesome framework to work with.

As I am jumping into creating my application I did come across a neat or useful way to structure your views so that you can allow the administrator of the site to select which template they want to use.

Before I jump in I do want to say that I create one layout.php file and this file is the whole layout which an include command for the body or content section.

First off with the default directory structure it looks like this:

/system/
/system/application/
/system/application/views/
index.php

Now what I do is create sub folders under the views folder like this:

/system/
/system/application/
/system/application/views/
/system/application/views/default/
/system/application/views/coolnew/
index.php

As you can see from that I now have two template directories default and coolnew.

Now I create a new model file. I name mine init_model.php and include this code:

<?php
class Init_model extends Model {

    function Init_model()
    {
        parent::Model();
		$this->obj =& get_instance();
    }

	function getSettings()
	{
		$this->settings['template']='default';
		return $this->settings;
	}

	function displayTemplate($template, $data)
	{
		$data['body'] = $this->load->view($data['settings']['template'].'/'.$template, $data, true);
		$this->load->view($data['settings']['template'].'/layout.php',$data);
	}
}
?>

Basically what this class does is when it is initialized it sets the template directory they want to use. I hard coded in default but this would normally come from the database. Next the displayTemplate function handles loading the correct template and body file. That way all your load->view is in one location and you can go back later and make any changes.

Inside my controller I use this code to call the view:

$this->init_model->displayTemplate('index.php', $data);
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • TwitThis

Responses

December 23rd, 2008 at 1:24 pm

Here is another link to a similar tutorial:
http://68kb.com/2007/10/28/templating-with-codeigniter/

Comments