Saturday, February 18, 2012

Codeigniter: Working with template views

Codeigniter doesn't provide a template engine, and it makes that each views has all html code.
Including files is a good idea, but I'm not happy adding every time de include code, is not DRY.

Well the best way to work with templates is the Decorator Design Pattern, and for make it possible in Codeigniter I was used the Most Simple Template Library for CodeIgniter until that discovered the next: Using another view like template.

Using it is very easy, is not neccesary use other library and you can add any functionality.

How to make it.

Simple use

Controller
public function action(){
   $data = array(
     'view' => 'view_name',
     'title' => 'Hello World'
   );
   $this->load->view('template_tpl', $data);
}

View
php  + view html

Template view
php + general html
$this->load->view($view);
php + general html

File system
/application/views/template_tpl.php
/application/views/view_name.php


Advanced use

If you use different sections in your site/application the simple use is not ver helpful. Following the same philosophy you can make possible it.

Controller
public function action(){
   $data = array(
     'section1' => 'section1',
     'section2' => 'section2',
     'view' => 'view_name',
     'title' => 'Hello World'
   );
   $this->load->view('template_tpl', $data);
}

View
php  + view html

Section
php  + section html

Template view
php + general html
section($section1);
php + general html
$this->load->view($view);
section($section2);
php + general html

File system
/application/views/template_tpl.php
/application/views/view_name.php
/application/views/section_name.php


Solve a little problem

To work with sections, we need to solve a little problem: If you don't send a section name to template, codeigniter show the next error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: variable_nameFilename: views/file.php
Line Number: x
To solve it we need to add this function to our template:
function section(&$name){
    $CI = & get_instance();
    isset($name) ? $CI->load->view($name) : null;
}




No comments: