Special Offer - Get $90 Discount and Host Your Dream Web Site @ Dreamhost for 1 Year Click Here. Promo Code SLJ345
Back To Top
WordPress Web Application Development
Develop Powerfull Web Applications Using Cutting Edge WordPress Development Techniques

Introduction to Templating and Dynamic Views with Codeigniter

on 2011/05/23 4:54 AM stored in: Uncategorized and tagged:

Introduction to PHP Templates with Codeigniter Parser and Views

Templates in php are used to separate user interface html code from the server side php code. Main functionality in templates is to separate the design elements so that even designers can change the templates without bothering about php code. Hence both the programmers and designers are able to change templates whenever they want without affecting other ones codes.

 

Also templates can be used to increase the reusability in a web application. Consider a web site like a blog where header,footer and sidebar elements are common throughout every page. In such situations we can create 3 common templates and include it in every page without repeating the same code.


Codeigniter provides a templating solution using .php files. Codeigniter uses model-view-controller pattern and the views in codeigniter can be considered as templates as well. Since views contain raw php code to define logic it cannot be treated as 100% templating solution. Hence codeigniter has provided a basic templates solution by introducing parser template library. Parser class provides general templating functionality such as assigning variables,looping through data and including templates inside other templates.

 

Throughout the next section i am going to explain how to use views and parsers in codeigniter and compare two methods for advantages and disadvantages.

Loading and Assigning Variables to Templates

Since parser is a codeigniter library class you have to load it using the following code.

// Load Parser Library
$this->load->library('parser');

 

Assigning Variables to Templates using Views

Server side php code looks same for both views and parsers in assigning data. We can pass the data required for views using an array. Following 2 code snippets contain the controller class code and view file code for using codeigniter views.

 

Controller Class

$data = array(
               'header' => 'Header Name',
               'content' => 'Sample Content'
          );

$this->load->view('example_page_view', $data);

 

View File – example_page_view.php



My Blog


        

You can use print the variables to the html view file using the php echo statement with the array key assigned as the variable name. Lets see how to do the same thing with codeigniter parser class.

 

Assigning Variables to Templates using Views

 

Controller Class

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

$data = array(
               'header' => 'Header Name',
               'content' => 'Sample Content'
          );

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

 

View File – example_page_view.php



My Blog


        

{header}

{content}

Now you can see the difference between the normal view files and parser templates. In parser no php variables are defined inside the view file. Only 2 strings surrounded by ‘{‘ and ‘}’ are available. So any one who doesn’t have development knowledge does not have to worry about php code. They can just ignore the 2 strings as normal text content and continue with there design. Also since views contain only the html code it is easy to separate view logic from the business logic. Next ill show you how to include dynamically changing sub templates inside main templates using both views and parser.

Assigning Dynamically Changing Sub Templates to Main Templates

You can add dynamic sub templates inside a another template. This is essential in increasing reusability of your application. Lets take a look at this blog post page for example. There is common header and footer,blog post content and sidebar for displaying categories. So we can create 4 sub templates for this page and include in a main template to increase the reusability.

 

Controller Class Code


function __construct(){
        parent::Controller();
        $this->load->library('parser');
}

function blog_post(){

        $data = array(
               'title' => 'Title',
               'content' => 'Sample Content'
          );

        $content = $this->parser->parse('content',$data,TRUE);

        $data['content'] = $content;

        $this->generate_view($data);

}

function generate_view($data=''){

        $header = $this->parser->parse('header',array(),TRUE);
        $footer = $this->parser->parse('footer',array(),TRUE);
        $sidebar = $this->parser->parse('sidebar',array(),TRUE);

        $data['header'] = $header;
        $data['footer'] = $footer;
        $data['sidebar']= $sidebar;

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

}

 

  • In blog_post function I have passed the required data to content view since it changes dynamically according to the blog post. Then assign the returned content template to the $data array.
  • Next you can call the generate_view function with the assigned data.
  • In the above code i have defined a common function called generate_view and included header,footer and sidebar since they are common through all of my pages.
  • First parameter is the name of the view, next one is the data needed for the view. Since my simple 3 templates does not need dynamic data i have passed and empty array.
  • Third parameter set to TRUE means that templates output will be assigned to a variable instead of outputting to the browser. Default value for this parameter is FALSE and template will be output to the browser. since we are intending to use these templates inside a one main template i am assigning these templates to respective variables.
  • Then you have to add the 3 template variables to $data array in order to pass to main template file.
  • Next you can pass the $data array to example_blog_post main template file with parse method in codeigniter parser class.

 

View File – example_blog_post.php





My Blog


        

{header}

{content}

{sidebar}

{footer}

In the view file i have defined 4 template variables. Since our $data array contains all these variables we can directly print out the template content. In this method you can add sub template files inside main templates to achieve reusability.

Looping Inside Codeigniter Templates

Looping through database results is essential in developing lists or data grids in web application. In this section i am going to show you how to do looping inside view files as well as codeigniter templates.

 

Using View Files

Lets assume we have a database table named students which has 3 columns id,name and age. Now when we execute a select statement we get a database result set in the format of an array. The result array will contain sub arrays which has values for keys id,name and age. We can directly assign this database result set to the $data array and call the view file as shown below.

$result = mysql_query("select * from students");
$data['result'] = $result;

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

Inside the view file we have to use a php foraech loop and bunch of php code to display the data to the browser. This is not recommended in templating since people without technical knowledge will not understand this code section. So we have to avoid php code as much as possible inside view files. Next section ill show you how to do this using parsers.


$row){
                echo "

".$row['name']."

"; echo "

".$row['age']."

"; } ?>

 

Using Codeigniter Parsers

Following code shows you how to use looping with parsers. When we use array for assigning template variables it will automatically loop through the array. In here $data[‘result’] is multidimensional array and when we use ‘{result}’ like this it will traverse through each sub array print the name and age using {name} and {age} variables. This is very easy to understand since there are no php codes inside the template files.


{result}
        

{name}

{age}

{/result}

Whats Next in Templating

Make sure you divide the common html code into sub templates and include in the main templates. Reduce the php code as much as possible in templates so that any one will be able to understand the code.

Codeigniter templating system is a basic solution for templating. If you want to use advanced features in templating you have to use a complete templating framework like smarty. Smarty can be installed and used very easily with codeigniter. Feel free to comment or ask any questions about this post.

Leave a Reply

Follow Us On Facebook