-
Notifications
You must be signed in to change notification settings - Fork 0
Most Simple Template Library
Category:Libraries Category:Libraries::Template Engines
[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>
</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]
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'' [code] 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); } } [/code]
[h2] Advanced use [/h2] 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'' [code] 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);
}
} [/code]
Then you can define your page title directly in your controllers the standard way: [code] $data['head_title'] = 'Photos'; $this->template->load('mainTemplate', 'about', $data); [/code]
Author: [url=http://maestric.com]Jérôme Jaglale[/url]