CodeIgniter Template Library Loading Default View

1. Creating the Library

Create a simple library and load into controller or configure auto load which allowed you to load default template.

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

In application/libraries folder, create new file with same name as Template.php

2. Writing the Load Method

We used to load a template view by passing two parameters as view name and data to be passed to the views (optional).
Basically, we collected data and view content in default template, so there is no need to assign common template part again and again.
After creating library, we need to create template.php in views folder and assign template related part in that file.

This way we will be loading view into template which will helps to show different view files in common header footer

Library file:

application/libraries/template.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
    class Template 
    {
        var $ci;
        function __construct() 
        {
            $this->ci =& get_instance();
        }
    }
    
    function load($view_name = null, $data = null) 
    {
        if ( ! is_null( $view_name ) ) 
        {
            if ( file_exists( APPPATH.'views/'.$view_name ) ) 
            {
                $view_path = $view_name;
            }
            else if ( file_exists( APPPATH.'views/'.$view_name.'.php' ) ) 
            {
                $view_path = $view_name.'.php';
            } else {
                show_error('Unable to load the requested file: ' . $view_name.'.php');
            }
            
            
            $header = $this->ci->load->view($header_path, $data, TRUE);
            $body = $this->ci->load->view($view_path, $data, TRUE);
            $footer = $this->ci->load->view($footer_path, $data, TRUE);
            
            if ( is_null($data) ) {
                $data = array('body' => $body,'header'=>,$header,'footer'=>);
            } else if ( is_array($data) ) {
                $data['header'] = $header;
                $data['body'] = $body;
                $data['footer'] = $footer;
            }
        }
        $this->ci->load->view('templates.php', $data);
    }
?>

Default template file: create template.php in view folder

application/libraries/template.php

<!DOCTYPE html>
<html>
    <head>
        <title><?php echo $page_title; ?></title>
        <!-- Add css files here ->
    </head>
    <body>
        <?php echo $header; ?>
        <?php echo $body; ?>
        <?php echo $footer; ?>
        <!-- Add js files here ->
    </body>
</html>

How to use library:

Create view file having html as following:

welcome.php

<p>
    Hello world!
</p>

Inside controller function, we need to add data and call library function like following:

$data = array(
     'page_title' => 'page Title',
);
 
$this->load->library('template');
$this->template->load('welcome', $data);

You are done. Hope this helps!

Leave a Reply