Nov 21, 2009

Introduction To Templating - Templating your website with PHP

free web hosting
Open Discussion > MODERATED AREA > Tutorials

Introduction To Templating - Templating your website with PHP

HmmZ
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:

CODE
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
CODE
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.

CODE
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

CODE
$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.

CODE
$template=stripslashes($template);

make sure $template doesn't have slashes as it will become unreadable then

CODE
$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.

CODE
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() tongue.gif ) is done.
CODE
<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 tongue.gif
i think it's all pretty self-explanatory, if not...ask tongue.gif

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
CODE
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, laugh.gif )
CODE
<?php
############
#test.php######
#trap17 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='http://www.trap17.com'>Trap17</a>";
$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 &copy; 2005 TheHmmZ";
?>

whoosh, finally done wink.gif
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 smile.gif

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

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 tongue.gif ). 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
CODE
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
CODE
<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
CODE
<?php
function test(){
global $title,$main,$navigation,$footer;
include("example.php");
template($data);}

switch($action){
default:
test();
break;
}
?>


test.php
CODE
<?php
$main .= "This is an example<br>";
$main .= "This is defined with the main variable";
$navigation .= "<a href='http://www.trap17.com'>trap17</a><br>";
$navigation .= "This is defined with the navigation variable";
$footer .= "Copyright &copy; 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

 

 

 


Comment/Reply (w/o sign-up)

HmmZ
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:
CODE
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!

 

 

 


Comment/Reply (w/o sign-up)



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : introduction, templating, templating, website, php

  1. Creating Common Navigation For A Website: Part 2
    Newbies guide to creating common navigation with PHP (0)
  2. Rfi (remote File Inclusion) What Is It? How Do I Stop It?
    Another website security tutorial (0)
    In my continuing attempts to learn more about website security i am going to tell you about a
    classic attack called Remote File inclusion (RFI). RFI is exactly what it says really, it involves
    using (or including) code from one website on another website. So if i have a website : secure.com
    with a modular, dynamic system like: secure.com/index.php?module=home notice the GET variable on
    the end of the URL. If i enter "blah" instead of "home" i get either a blank page, or a 404: page
    not found error, there is also a chance you will get an error message like: Error: inclu....
  3. My First Website
    Where can i find useful web page templates? (14)
    Hi folks, Just wondering, as a newbie website builder, where can I get some useful HTML, CSS
    templates suitable for building a small business website? What is the best development environment
    for building websites? Is there a good open source program available?, or is it best to spend some
    money on something like Dreamweaver? Does anyone have experience of adding databases to Trap17
    sites, perhaps using Wamp server?....
  4. How To Create Pdf Files Using Free Tool
    Introduction to use a free tool to create PDF file (10)
    Now, that you don't need to have expensive software like Acrobat to create PDF. All you need is
    Microsoft Office and a software name doPDF. You can download the freeware from
    http://www.dopdf.com/download.php After downloading dopdf.exe, follow the instruction below 1.
    Double click to install it, as display at image 1.jpg, choose a language and click OK 2. You will
    see 2.jpg click next 3. Click I accept the agreement see 3.jpg, click next 4. Now you will see
    4.jpg, select the folder to install it and click next 5. When seeing 5.jpg, This is the folder group
    in Star....
  5. How To Setup A Website After Your Forum
    (3)
    This tutorial is about how to setup a website after you have setup a forum. That means, you have a
    forum, and are wanting to add a website. This tutorial will show you how to create the website in
    your root directory(Example: http://domainname.com) , while your traffic gets redirected to your
    forum while you are creating it, until you're ready for guests to see it. This method is
    opposed to setting it up in another directory, then moving it(particularly more time consuming if
    you're site is PHP based). First of all, you are going to want to setup a redirect ....
  6. Creating Navigation For Html Websites
    Have a common navigation menu for the whole website! (12)
    Pre-requisite: HTML, inline frame tags 1 Attachment(.zip) included. Updates : 29-12-07: Doctype
    added in example files (Advised by jlhaslip) Designing a whole website takes a lot of planning
    and organization. Designing a proper navigation system is a basic step in building your website. If
    you are developing webpages in html you would have observed that as you go on creating pages it
    becomes difficult to maintain the links to the pages. This article will guide you in developing a
    common navigation menu for your website. It describes three ways, so if you don'....
  7. Css Scroll Bar Styles
    Change the color of your website scrollbar! (1)
    REQUIREMENTS 1. Must have limited to good knowledge of CSS. 2. Must have limited to good knowlege
    of HTML. THE ELEMENTS First of all, there are 7 different elements of a scrollbar. a) Scrollbar
    Arrow Color /cool.gif" style="vertical-align:middle" emoid="B)" border="0" alt="cool.gif" />
    Scrollbar Darkshadow Color c) Scrollbar Track Color d) Scrollbar Face Color e) Scrollbar Shadow
    Color f) Scrollbar Highlight Color g) Scrollbar 3dlight Color Bassically all that you need to do is
    change the colors like you normally do with any sort of CSS. Therefore, if you want the....
  8. Making A One Page Does All Website In Phph
    (2)
    Hello and Great Day or Night either one. Have you ever been to a site and seen a index page or any
    page at all control everything such as index.php?do=home&action=logout something similar to the
    above? Well I am going to show you how easy it is to make this all own your own, and only have to
    use one web template or design to make it work. Before we get started you need to go ahead and find
    the web design that you want to use. After you find the site you want to use go ahead and save
    it... and save it like this so we can work together, ok! Note* We are going to be s....
  9. Adding Your Website To Google
    How to register with google (25)
    Hi everyone. Hopefully here im going to tell you how to register yourself with the Google search
    engine and get yourself in their results. Ill start the tutorial assuming you already have Meta
    tags or other search engine optimisation techniques in place. This tutorial is solely about
    registering with google. At one time i thought simply using meta tags etcetera would get you listed
    in Google, i then found out that didnt work, so i wondered why, and the fruits of my labour are what
    will go into this tutorial. the first step is to get a google account, this will get y....
  10. How To Make A Proper Introduction
    Not just: Hi, I am here. (7)
    How to make a proper introduction to Trap17 forum members. FIRST OF ALL READ THE TRAP 17
    FORUM RULES AND REGULATIONS Basic Rules In-depth Regulations Trap 17 has these
    rules and regulations to maintain some kind of order in this chaotic world; to keep the forum
    refreshing and informative, uncluttered by useless, redundant chatter. PLEASE follow them. After
    all this is all for FREE and keeps Trap 17 up and running. Who are you? (You
    needn't use your legal name, but give us something to call you that is an indicator of you....
  11. Templating System Using Php Includes
    Building a Dynamic site using Includes and flat-files. (13)
    Php based Templating System http://jlhaslip.trap17.com/template/index.php The Source Code
    for the scripts are included (literally) on the different pages on the Demo, including the Contact /
    Email script. The only page not there yet is the Message Script. Maybe tonight I will upload that.
    This one uses a little bit of query-string checking to confirm that the contents of the page are
    actually available (file_exists())and an allowed page content before serving it up. The
    'allowed page content' is done by checking against a flat-file containing an array....
  12. Checking Dns Settings For Website
    DNS Setting, Ping, Whois, Dnsreport etc (2)
    If you have recently purchased a domain and facing problems with the workings, the first thing which
    you should check is the DNS setting. Dns settings determine, how to domain is pointed to the Server
    and How the server is connected to the world (internet). Ensure, the DNS settings are perfect to
    make sure, things work smoothly and people across the globe don't have problems accessing your
    site. The basic check would be : PING Suppose you register your domain (example.com) at
    ComputingHost. You get an IP for your website. In this case, suppose its 64.69.35.170. Yo....
  13. Configuring Dns Settings For Website
    Nameserver, A-Address, DNS configuration (1)
    Most of the people have problems configuring their website. After registering their domain, many get
    confused in configuring their domain (basically the DNS settings). This small tutorial will help you
    get started with DNS settings configuration. A domain can be basically pointed to a server using 2
    main techniques. 1. Nameserver (the most recommended way) 2. A Address (Not recommended)
    Configuring using Nameservers ==================== Login to your domain Control panel provided by
    your DOMAIN NAME PROVIDER / REGISTRAR. Not your webhost. Search for settings like DN....
  14. Changing Background Color In Php
    usefull for templating. (5)
    Tutorial on how to change background color with PHP I will be descibing to similiar ways that
    you can change the background color of your website with php and leave it at that till the user
    changes it again. We are going to do this with CSS. You can either have your cSS info on your page
    or in a spereate document. The first thing youll have to do is decide if your going for the linked
    stylesheet or directly on your page. IF you link it you'll need to have this code in you
    tags. CODE This isnt actualy real linking because i dont think you can li....
  15. An Introduction To Java And Graphics
    (5)
    Table of Contents I. Introduction II. Before You Begin III. Necessities in a Java Program IV.
    Creating a Canvas V. Shapes A. Line B. Rectangle C. Oval D. Polygon VI. Other Things A.
    Changing the Color B. Strings 1. Changing the Font 2. Drawing a String C. Images VII.
    Conclusion I. Introduction Welcome to my second tutorial here at Trap17. I'm going on
    vacation for a week so I thought I'd leave you all with some of the things that I picked up in
    the class I took ealier this summer. If anyone wants to see some things that I've done, t....
  16. Centered Website With Two Columns
    CSS (12)
    This is upgrade of my first tutorial for Centered website with fixed width. Today I am going to
    present you tutorial for making two columns website with fixed width. My basic tutorial can be found
    here: here. So let's begin: First we will change CSS file, everything stays same if not
    mentioned to change, starting with color of content from basic tutorial, change background to this
    code. This will actually be background of left column and padding will be set to 0, cause it will be
    defined in Left and Right column. New code for Content: CODE #Content{  width:....
  17. Centered Website With Fixed Width
    ...begginers lesson... (2)
    This will be tutorial on how to make a simple website design with fixed width and center position.
    This is actually rather simple tutorial, but hopefully it will help others that are new in world of
    creating websites. Website will also contain header, content area and footer. First we must do
    Wrapper. Wrapper is actually an area of fixed width and will be position into center, so that our
    page doesn't fall apart. CODE body{ width:100%;  margin:0px;  padding: 0px;
     text-align:center; background:#FFFFFF; } This is actually an IE5 hack were we did c....
  18. Secure The Email Addresses On Your Website!
    Wonderful script and useful! And working (10)
    Just follow the instructions below: /* Secure Email Function by Juan Karlo Aquino de
    Guzman Website: http://www.karlo.ph.tc and http://www.abs-cbn.ph.tc E-mail:
    http://www.karlo.ph.tc/send.php Usage: showEmail("support@microsoft.com",0); OR
    showEmail("support@microsoft.com",1); Types: 0 = ordinary random 1 = more secure random To
    include to a script: include_once("email_secure.php"); */ And here is the code :
    CODE /*     Secure Email Function by Juan Karlo Aquino de Guzman     Website:
    http://www.karlo.ph.tc and http://....
  19. Php Sockets
    Introduction to an underused function of PHP (4)
    This tutorial is based on a question written in the PHP programming board Inspiration
    Introduction Sockets, an underused function in PHP, is a function that enables you to open
    connection to other peoples computers and vice versa. By sending commands to the operating server,
    it will first see if there's response, then, it sends or receives data that the operating server
    has available. Creation of a socket Of course, a first step in using sockets, is creating it,
    this is done by: CODE resource socket_create ( int domain, int type, int protocol) and a ....
  20. E-mail Mailer Script 0.1
    useful for website visitors (4)
    Are you pissed off when you are putting e-mail in your website, you always get spammers? Well,
    here's the solution. Just change the default variables to anything that you like, etc... follow
    the instructions on the script.. Here it is... hope you like it /smile.gif' border='0'
    style='vertical-align:middle' alt='smile.gif' /> CODE //E-mail Mailer Script 0.1 by Juan
    Karlo de Guzman //FOR TRAP17 ONLY... DEMO VERSION... DO NOT DISTRIBUTE header("Content-type:
    text/html; CHARSET=UTF-8"); $int_rand=mt_rand(1,20); if($int_rand>10) {
    $random_numbers=sha1(mt_ra....
  21. Making A Website
    Also Some Dos and Don'ts (6)
    I had originally had this posted on my domain at nevernormal.com, and thought that you guys could
    use it here as well. Granted, this is geared to the uber newbie, so don't razz me if I
    don't suggest the most advanced in web design. lol So, you want to make a website? 1.
    First, think about what you want your site to be about. There are fanfic sites, like Drastic
    Measures and fanfiction.net ; cliques or clubs, like the BtVS Writers' Guild ; or, if you
    want, you could have a general site, whether it be about a show/movie you like, or even just about y....
  22. A Little Introduction To 3d Studio Max
    How to make a simple abstract image (11)
    This tutorial will teach you the basics of making abstract images in 3D studio max. In this example,
    I used a simple sphere, and applied the “Noise” modifier. Then, I applied a transparent, blue,
    plastic-like material to spice up the whole thing. Let’s start. First, make a sphere by selecting
    the “Sphere” button in the “Standard Primitives” section, and draw somewhere in the center of the
    perspective view. We will set the size of the sphere later on. The sphere I made looks like this,
    yours can be different in size and color, but the only thing that is important is to....
  23. [tutorial] Skinning Your Site
    a tutorial on how to skin your website (2)
    For this tutorial you are going to need to know how to use php includes. You are also going to need
    to rename all o your files to a .php extension. In your FTP or Cpanel make a folder in your public
    (main) directory and name it "skins". In the skins folder make another folder named "1". In the
    folder you names skins make a file called cookiecheck.php. Copy the code below and paste it into the
    cookiecheck.php file. $total_skins = 1; $default_skin = 1; if (isset($_REQUEST )) {
    $newskin=(int)$_REQUEST ; if ( ($newskin $total_skins) ) $newskin=$defau....

    1. Looking for introduction, templating, templating, website, php
Similar
Creating Common Navigation For A Website: Part 2 - Newbies guide to creating common navigation with PHP
Rfi (remote File Inclusion) What Is It? How Do I Stop It? - Another website security tutorial
My First Website - Where can i find useful web page templates?
How To Create Pdf Files Using Free Tool - Introduction to use a free tool to create PDF file
How To Setup A Website After Your Forum
Creating Navigation For Html Websites - Have a common navigation menu for the whole website!
Css Scroll Bar Styles - Change the color of your website scrollbar!
Making A One Page Does All Website In Phph
Adding Your Website To Google - How to register with google
How To Make A Proper Introduction - Not just: Hi, I am here.
Templating System Using Php Includes - Building a Dynamic site using Includes and flat-files.
Checking Dns Settings For Website - DNS Setting, Ping, Whois, Dnsreport etc
Configuring Dns Settings For Website - Nameserver, A-Address, DNS configuration
Changing Background Color In Php - usefull for templating.
An Introduction To Java And Graphics
Centered Website With Two Columns - CSS
Centered Website With Fixed Width - ...begginers lesson...
Secure The Email Addresses On Your Website! - Wonderful script and useful! And working
Php Sockets - Introduction to an underused function of PHP
E-mail Mailer Script 0.1 - useful for website visitors
Making A Website - Also Some Dos and Don'ts
A Little Introduction To 3d Studio Max - How to make a simple abstract image
[tutorial] Skinning Your Site - a tutorial on how to skin your website

Searching Video's for introduction, templating, templating, website, php
See Also,
advertisement


Introduction To Templating - Templating your website with PHP

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com