A basic template engine that seperates the business logic from display logic.
The basic idea of this template system is to implement a light weight MVC patter.We use only two PHP functions
- ob_start();
- ob_get_clean();
Advantages:
- With this php template system we can include nested templates also.
- since this php template system does directly php code it performs much faster.
- very light weight.
ob_start()
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. This buffer can be retrived to a string variable using ob_get_contents().
ob_get_clean()
Gets the current buffer contents and delete current output buffer. this buffer in turn returns as a string like ob_get_contents().
To test this template system download the example files and see the example1.php,example2.php
Template Class
class template { function template() { } function get($path, $params = array()) { ob_start(); extract($params); include ($path); return ob_get_clean(); } } |
Example
include 'template.class.php'; $tpl=new template(); $tvars=array(); $tvars['name']='Mahesh'; $tvars['arrayvars']=array( array(1,'Apple'), array(2,'Mango'), array(3,'Banana') ); $tvars['nestedtemplate']=$tpl->get('template.nest.tpl.php',array()); echo $tpl->get('template2.tpl.php',$tvars); |
Output


