[This is my re-post from another site that I have written an article with title
Simple Template Engine Basic Architecture
on Sun Aug 02, 2009 3:33 am ]I would like to show the newbies a simple 15 line code, how a basic template engine in php works
create two folders in side your website as follows
- templates
- cache
Create index.php in your root folder and index.html inside template folder
Open index.php in your favorite editor [I use, netbeans or dream weaver] and add the following code and save. Make sure your cache folder has read / write permission
[code]
- <?php
- //Author: Najeem M Illyas, Chief Software Architect, tcc247.com
- $tpl_var = array('{DOC_TITLE}','{BODY_BGCOLOR}','{BODY_CONTENT}');
- $tpl_values = array('Test Title','#6633ff','This is my first template engine project<br /> -Najeem M Illyas');
- $fp = fopen('templates/index.html','r',false);
- $read_data = fread($fp,filesize('templates/index.html'));
- $new_data = str_replace($tpl_var, $tpl_values, $read_data);
- fclose($fp);
- if($fp = fopen('cache/index.html.php','w',true))
- {
- fwrite($fp,$new_data,(filesize('templates/index.html')+1024));
- fclose($fp);
- include_once('cache/index.html.php');
- }
- ?>
[/code]
Open index.html and add the following
[code]
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>{DOC_TITLE}</title>
- <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
- </head>
- <body bgcolor="{BODY_BGCOLOR}">
- {BODY_CONTENT}
- <br />
- This is html text
- </body>
- </html>
[/code]
Now the code:
The code in php is for reading the html file and making a simple buffer and then the template variables are replaced with array values in the buffer and finally writing the new data in the buffer to new file index.html.php. This file is included to the index.php file for demonstrating the final result. Now you can see the variables are replaced with values from array. This concept can be expanded to any desired level for making big systems like Smarty etc.
Run the index.php file and you will find generated file in cache folder.
Here we are utilizing the power of PHP.
Regards,
Najeem M Illyas
http://www.manchesterinfoservices.com/