-
Notifications
You must be signed in to change notification settings - Fork 0
Simple Template Library
Category:Libraries Category:Libraries::Template Engines This is a small template class that I am currently using on a university project.
[h2]Setup[/h2]
-
Create [b]Template.php[/b] in [b]system/libraries[/b].
-
Open [b]config/autoload.php[/b] and add template and parser as shown below. [code]$autoload['libraries'] = array('template','parser');[/code]
[h2]Source[/h2]
[h4]Template.php[/h4] [code] <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /**
-
Template Class
-
Template View Parse Class
-
@package CodeIgniter
-
@subpackage Libraries
-
@category Templates
-
@author Koola
-
@link */ class Template {
/**
- Constructor
- @access public */ function __construct() { log_message('debug', "Template Class Initialized"); }
// --------------------------------------------------------------------
/**
- Load template
- @access public
- @param String
- @param Array
- @param Array
- @param bool
- @return parsed view */ function load($template = '', $view = array(), $vars = array(), $return = FALSE) { $this->CI =& get_instance(); $tpl = array();
// Check for partials to load if (count($view) > 0) { // Load views into var array foreach($view as $key => $file) { $tpl[$key] = $this->CI->load->view($file, $vars, TRUE); } // Merge into vars array $vars = array_merge($vars, $tpl); }
// Parse template return $this->CI->parser->parse($template, $vars, $return); } } ?> [/code]
[h4]application/views/about.php[/h4] [code]
You just called your first template!
Page rendered in {elapsed_time} seconds
[h4]application/views/main.php[/h4] [code] <html> <head> <title>{title}</title> <style type="text/css"> body { background-color: #fff; margin: 40px; font-family: Lucida Grande, Verdana, Sans-serif; font-size: 14px; color: #4F5155; } h1 { color: #444; background-color: transparent; border-bottom: 1px solid #D0D0D0; font-size: 16px; font-weight: bold; margin: 24px 0 2px 0; padding: 5px 0 6px 0; } </style> </head> <body>
</body> </html> [/code]
[h4]application/controller/home.php[/h4] [code] <?php
class Home extends Controller {
function __construct()
{
parent::Controller();
}
function index()
{
$data['title'] = 'My page title';
$partials = array('content'=>'about');
$this->template->load('main', $partials, $data);
}
} ?> [/code]
[h2]Operation[/h2]
Calling multiple views is easy:
[code] $partials = array('content'=>'article','head'=>'header','footer'=>'footer'); [/code]
Key in the array above is the meta parse code (i.e. {content} ) that resides in your master template file. Value is the filename to call from your views directory.
To render the template use: [code] $this->template->load('main', $partials, $data); [/code]
Main in the above code is the Master Template file in which parse tags should be placed.
Partials is view array.
Data passes array data just like a view call.