Archive for the ‘Sample Codes’ Category

Page template in CodeIgniter

Thursday, May 27th, 2010

In normal PHP development, we usually made a template to be use for any other pages that has content. Usually the template page contains section like header, content and footer (this is default).

In CodeIgniter there is 3 way to do that, by using CodeIgniter’s built in parser, some external method and using external libraries made by community.

1. CodeIgniter’s built in parser

CodeIgniter’s aware of this problem and already made their solution by introducing template parser class. To use this class, simply load the library into your controller code:

1
$this->load->library('parser');

Suppose your template called template1.php and the contents of the template is like follows:

1
2
3
4
5
6
7
8
9
10
<html>
<head>
<title>{title}</title>
</head>
<body>
 
<h3>{heading_title}</h3>
<p>{body}</p>
</body>
</html>

Additional code in controllers to pass on template was:

1
2
3
4
$data = array(
            'title' => 'My Blog Title',
            'heading_title' => 'My Blog Heading'
            );

All data need to pass on template need to be inserted into an array with the key named exactly like those in curly brackets inside template page. Finally parse the template together with the array of data created.

1
$this->parser->parse('template1', $data);

2. Ask about PHP method

Ask about PHP shared their method of how to have a template with just using normal view in CodeIgniter. Their explanation was here.

3. External community library

Jérôme Jaglale had came out with library that really helpful. Further explanation are on his page. Downloadable copy of the library are also there.
Most Simple Template Library for CodeIgniter