Jump to content
xisto Community
Sign in to follow this  
HmmZ

Introduction To Templating Templating your website with PHP

Recommended Posts

Pre-note

Hello and welcome. if your website doesn't use a templating function, you may have noticed it's pretty hard to update your website (layout) unless you dig through many files to update the images and such.

 

The solution is templates. If you ever got curious and looked into phpBB codes or any other template based forum/CMS, you saw the .tpl files they use. I am not at a point where i base everything on .tpl (simply because i havent taken the time to see how it all works). But i do can tell you that it's the same principle, template your site using an external .html file. That is the incentive of this tutorial

 

Comments

First i wanna say that this isn't a ripped tutorial. (ive been accused in the past aswell)

Second, this is a custom and pretty easy way of templating, ill even explain (short) how to get a theme preference from a user.

 

First off...functions file

I'm making this look like a huge tutorial, but it isn't. If you use a functions file (where you have all functions() defined) you may want to place the template() function in there aswell.

I will first show an example template function, and then explain:

 

 

function template($content){global $title,$main,$bar,$nav,$right,$footer;get_theme();$file="$theme/theme.html";if(!$rf = fopen($file,"r")){$error=1;}else{$template=fread($rf,filesize($file));fclose($rf);$template=stripslashes($template);$template=eregi_replace("<% title %>","Solarity Gaming",$template);$template=eregi_replace("<% main %>","$main",$template);$template=eregi_replace("<% bar %>","$bar",$template);$template=eregi_replace("<% datetime %>","".date('d-m-Y H:i:s \G\M\T\+\0\1\0\0')."",$template);$template=eregi_replace("<% nav %>","$nav",$template);$template=eregi_replace("<% right %>","$right",$template);$template=eregi_replace("<% footer %>","$footer",$template);print "$template";}}
This is the exact template() function i just copy pasted from my functions file, i wont edit it to make it easier, since it isnt that superhard

 

explanation

function template($content){global $title,$main,$bar,$nav,$right,$footer;
This is the start of the function, later on, you will see that template($content) has a reason and that the globals are pretty important, as they fetch the variables from your include file.

 

get_theme();
Here i'm calling the get_theme() function, because we will be calling the theme.html later this file, it makes sure the right theme is stored in the $theme variable

 

$file="$theme/theme.html";if(!$rf = fopen($file,"r")){$error=1;}else{$template=fread($fd,filesize($file));fclose($fd);
the variable $file defines the location of your theme.html, $theme was defined earlier through the get_theme() function

the if...else function makes sure theme.html is readable, if its not readable, nothing much happens, if it is readable, then $template is defined, $template will later on make sure the template variable (for example <% main %>) is fetched from theme.html correctly, to configure it.

 

$template=stripslashes($template);
make sure $template doesn't have slashes as it will become unreadable then

 

$template=eregi_replace("<% title %>","Solarity Gaming",$template);
I won't display all theme variable defines, because it all is the same.

the predefined $template is getting a new definition, its pretty double, because in the same line $template has 2 completely different meanings.

Anyway, in this line, the theme variable <% title %> is replaced with "Solarity Gaming", wich means, once template() is called, the page would have the title Solarity Gaming,

in other lines the theme variable is stored in a php variable (<% main %.,"$main")

wich means that once template() is called later, all $main defines in the included file will replace <% main %> in the theme.html.

 

print "$template";}end else}end function
we have defined $template (with alot of info), so we print it, then we close the function, the function is ready to be used, lets make theme.html!

 

theme.html

If you followed me to this far, you are doing great, the hard part (atleast for me, took me ages to explain template() :D ) is done.

<head><title><% title %></title><link rel="StyleSheet" href="themes/default/style.css" type="text/css"></head><body bgcolor="#E3E3E3"><center><table id="box" cellspacing="0" cellpadding="0">	<tr>      <td>  	<table id="box2" cellpadding="0" cellspacing="0">    <tr>    	<td id="banner">                      	</td>    </tr>    <tr>    	<td id="bar">    	<% bar %>&bsp;<% datetime %>    	</td>    </tr>    <tr>    	<td>      <table id="box3" cellspacing="0" cellpadding="0">      	<tr>        <td  id="Navigation" align="right" valign="top">                <% nav %>        </td>        <td style='background-color: #DCE5EE;' valign='top'>            <% main %>        </td>        <td id="Right">        </td>      	</tr>      </table>    	</td>    </tr>    <tr>    	<td id="Footer">         <% footer %>    	</td>    </tr>  	</table>        	</td>    	</tr></table></center></body>
ooo creepy huh? I though that bursting the code in your eyes would be less hurting in the long run :D

i think it's all pretty self-explanatory, if not...ask :D

 

calling template()

Basically everything is done, you have defined template($content), enabling it to template anything you desire. you got your theme.html that defines the locations of where the variables should be placed...There is 2 things left that might need explaining...calling template() and the file you wish to template

 

calling template is as easy as 1,2,3

function test(){global $title,$main,$bar,$nav,$right,$footer;include("test.php");template($data);}
ive found my comfort way to call template() through functions, it gives an easy overview over files and is easy to edit or anything.

Now, whenever test() is called, it will include test.php and then template the data found inside ($data is a more general way to get all the $variables)

 

i don't think calling template needs more explaining, but please yell if you do need some more explaining

 

test.php

i made the function test() instead of copy pasting functions im using (simply because it would be too confusing). But i can tell you, once you get the hang of templating, you can do great stuff with your functions and maybe even learn new stuff, cause, as you can see, it's not that hard to create stuff ^^

 

Anyway, back on topic, we have included test.php, so what would it look like (o god now i gotta make that too, ;) )

<?php#############test.php#######Xisto tut##################define $main variable##this would be anything in the middle##the REAL content such as news#$main .= "Hello this is a test";$main .= "<br> a test to see if i got this templating crap of the hmmz to work";$main .= "whoa im seeing it!? it must have gone great!";#define $nav variable##nav as in navigation##<% nav %> got defined to fit at the left of your page##so lets make some links!#$left .= "<a href=''>";
$left .= "<br> HAHA! links work too? AWESOME!";#define $bar variable##lets set it up with a login form?#$bar .= "<form method='post' action='index.php?action=login'>";$bar .= "Username : <input type='text' name='user'>";$bar .= "<br> Password: <input type='password' name='pass'>";$bar .= "<input type='submit' value='login'></form>";#define $footer variable##as its name says it will be at the foot of your page##so lets define it with a copyright?#$footer .= "Copyright © 2005 TheHmmZ";?>
whoosh, finally done :D

Anyway, i have defined all the variables in just 1 file, to make it a bit easier on your side, but you can use many different files, i do think that defining the same variable (for example $main) in multiple files would cause a lot of mayhem, so dont ;)

 

Note: the # is used for commenting, just like //. I just like # more :D

 

this file will be included, and, as expected your file should be displaying everything on the right place, just try it. if you want a full example, get the codes at the of this tutorial.

 

Conclusion

Well, you got to be honest, it wasn't THAT hard to understand, not much needs to be done to prepare your website for a real templating engine (expensive word, low costs :D ). for existing websites with alot of files and such, it can get tough. but a tip would be to open the file you want to fix for templating in notepad, then ctrl+h type in print " or echo " and make the replacement word for example news $main .= " this will remove print " and replace it with $main .= "

 

Hope you enjoyed this tutorial and that it helps you, any questions i will gladly answer

 

Full Example

functions.php

function template($content){global $title,$main,$navigation,$footer;$file="themes/theme.html";if(!$rf = fopen($file,"r")){$error=1;}else{$template=fread($rf,filesize($file));fclose($rf);$template=stripslashes($template);$template=eregi_replace("<% title %>","Example",$template);$template=eregi_replace("<% main %>","$main",$template);$template=eregi_replace("<% navigation %>","$navigation",$template);$template=eregi_replace("<% footer %>","$footer",$template);print "$template";}}
theme.html

 

<head><title><% title %></title></head><body><table> <tr>  <td>   <table>    <tr>     <td>       <% navigation %>     </td>     <td>       <% main %>     </td>    </tr>   </table>  </td> </tr> <tr>  <td>    <% footer %>  </td> </tr></table></body>
index.php

 

<?phpfunction test(){global $title,$main,$navigation,$footer;include("example.php");template($data);}switch($action){ default: test(); break;}?>
test.php

 

<?php$main .= "This is an example<br>";$main .= "This is defined with the main variable";
$navigation .= "";
$navigation .= "This is defined with the navigation variable";$footer .= "Copyright © myself<br>";$footer .= "example made possible by TheHmmZ<br>";$footer .= "This is defined with the footer variable";?>
fileroot

ROOT/functions.php

ROOT/index.php

ROOT/themes/theme.html

ROOT/test.php

Share this post


Link to post
Share on other sites

Note that it's extremely easy to have multiple themes, letting the user choose himself

as ive stated before with the get_theme() function, the get_theme() function is fairly small:

function get_theme(){$get_pref=mysql_query("SELECT theme_pref FROM users WHERE username='".$_SESSION['user']."'");if(!$get_pref){$theme="themes/default";}else{$theme="themes/".mysql_fetch_object($get_pref)."";}}

what my get_theme() function basically does is get the theme preference of a user in the users table, and change the $theme variable to the preferred one, this only changes the theme for the user itself and not the whole site. Making it very versatile even though it's just a small piece of code.

Note that if the sql query is unable to be executed (its a guest or sql server is down (templating itself is not sql-based)) it chooses the default theme.

Enjoy! Any questions or suggestions? dont hesitate and reply!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.