Skip to content

Most Simple Template Library

World Wide Web Server edited this page Jul 4, 2012 · 26 revisions

Category:Libraries Category:Libraries::Template Engines

Author: Jérôme Jaglale (http://maestric.com)

[h2]Example[/h2] To load a view into a template, instead of [code] $this->load->view('about', $data); [/code]

just use: [code] $this->template->load->('mainTemplate', 'about', $data); [/code]

This will load the view about.php into the template mainTemplate.php.

[h2]Installation[/h2]

  • Put Template.php in the "libraries" folder
  • Autoload it: in config/autoload.php: ''$autoload['libraries'] = array('template');''

[h2]How to use it[/h2]

[h3]Create a template file[/h3] ''views/mainTemplate.php'' [code] <html>

<head> <meta name="author" content="Who am I?" /> </head>

<body>

Cooking by yourself is worth!
<?php require_once($template_contents.'.php'); ?>
Don't try contact me, I've got more interesting things to do than answering to perfect strangers' emails.

</body> </html>

[/code]

The magic comes with this line: [code] <?php require_once($template_contents.'.php'); ?> [/code] which indicates where your view code will be inserted.

[h3]Create a view[/h3] ''views/about.php'' [code]

Template Library for Code Igniter.

Ladies and gentlemen, yes, that's unbelievable!

[/code]

[h3]Load the view into the template[/h3]

In a controller's method: [code] $this->template->load('mainTemplate', 'about'); [/code]

[h2] How it works [/h2] The source code is incredibly short and straightforward: ''libraries/Template.php'' class Template { function load($template = '', $view = '' , $vars = array(), $return = FALSE) { $vars['template_contents'] = $view; $this->CI =& get_instance(); return $this->CI->load->view($template, $vars, $return); } }

===== Advanced use ===== Life is not so simple. You'll probably need more slots in your template, for example for the page's title. To keep the code readable, I write one method for each template: ''libraries/Template.php'' class Template { function load($template = '', $view = '' , $vars = array(), $return = FALSE) { $this->CI =& get_instance(); $vars['template_contents'] = $view; if ($template == "mainTemplate") return $this->loadMainTemplate($view, $vars, $return); else return $this->CI->load->view($template, $vars, $return); }

    function loadMainTemplate($view, $vars = array(), $return = FALSE)
    {
            if( ! isset($vars['head_title']))
                    $vars['head_title'] = "Default Title";

            return $this->CI->load->view("mainTemplate", $vars, $return);
    }

}

Then you can define your page title directly in your controllers the standard way: $data['head_title'] = 'Photos'; $this->template->load('mainTemplate', 'about', $data);

Clone this wiki locally