Jul 24, 2008

Introduction To Templating - Templating your website with PHP

Free Web Hosting, No Ads > CONTRIBUTE > Tutorials

free web hosting

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

 

 

 


Reply

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!

 

 

 


Reply



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*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Similar Topics

Keywords : introduction, templating, templating, website, php

  1. Another Boring New Member Introduction
    the title says it all (6)
  2. I Cannot See My Website Or Log Into Cpanel
    (7)
    Ok, I finally got my form approved after that massive wait because of some issue and now, my
    computer decides not to load up my site! - My site does not load up on either browser, I cannot
    ping it (but it resolves the IP) - It loaded ONCE. And never after that - It's not my network, I
    used my neighbors wireless to verify that Can anyone help me? PS. I am samlockart.trap17.com....
  3. Hi Everbody
    An introduction of my personallity ... (5)
    Hello boys and girls/lady's and gentleman's ... My name is Goran,I'm coming from
    Croatia,but now I'm living in Bosnia and Herzegovina ... (my Eng. is bad,very bad ... ) I'm
    very interested in this programing *BLEEP* and all the other crap. For me,most interesting system is
    PHP Fusion ... I always wondered is there a better CMS , but it looks like PHP Fusion is,unlikely of
    Joomla, old fashion,but I actually like it /tongue.gif" style="vertical-align:middle" emoid=":P"
    border="0" alt="tongue.gif" />....
  4. I Can && Cannot Acces My Website
    Confusing issue. (4)
    I am a hosted member in trap17 and my domain is www.karunya.cc . I have been not able to access my
    website for few days and i had PM'd the admin and he provided me great support,but still i have
    some confusion , so please anyone help me . My domain was now accessible using my true IP . On the
    other hand if i use a Proxy i am able to access my website , so i had given my true IP's
    220.225.140.98, 210.212.244.4 to Xisto to check whether they are in the IP ban List in Xisto
    firewall , the internet im using is provided by my college and im sure here there is not ....
  5. Need Help To Increase The Page Rank Of Website!
    (2)
    Hi everybody, I am dealing in online business and looking for some tips to increase the page rank of
    my website. In this I need some helps from you people. Please suggest me some tips so that I can get
    good traffic to my website and get more benefits. Your any suggestion will be highly appreciated.
    Thanks in advance! ....
  6. Website Optimization Help
    (0)
    Hello everyone. I need a little help with optimization. I have a great site that delives
    information to a lot of people but Google is just starting to cost too much with their adwords... I
    am wondering if there is anyone who can help with optimization. Any tips and/or tricks are greatly
    appreciated, and the address of the website is http://www.stockpreacher.com thanks all...Cheers....
  7. Introduction
    (5)
    Hello to everyone here at Trap17. My name is jobel602 - or John for short, and I live in Cornwall in
    the UK. I do have a website and I know everything about them except how to make them , how to host
    them or where I should begin; so,I ended up here. I spent ages trying to find somewhere where I
    could have a banner or script hosted without having to plough through hundreds of ads or have them
    cluttering up my site. I was amazed at the amount and variation of topics here at Trap17 and I am
    sure that I have plenty of reading to do before I have the confidence to post ....
  8. Free Domains For Bloggers
    My Website Idea (3)
    Note: I tried to post this in the Internet Section but cudn't so i'm posting it here I have
    this idea to build this website that will provide free domains to bloggers. The idea is simple. I
    will take donations from people and applications from bloggers and will provide domains to bloggers
    who have the potential to be successful. This is because despite the fact that domains are cheap,
    many people cant afford to buy them or cant because of other constraints. And any one knows that to
    have a successful blog you need a top-level domain. What do you think? Is this....
  9. Best Way To Make Money From Your Website?
    (5)
    I'd like to start a website that offers a free service, yet in order to keep this service going
    I will need a small income...any ideas? I know about adsense and whatnot but I would like something
    more.....
  10. Has Anyone Designed A Website For A Wow Guild?
    (0)
    I belong to a WOW guild and we're considering a website for our members. Has anyone any
    experience designing and running such a site? For a start, we're only interested in a basic
    website for our members so we can show member character stats, announce raids and have a forum so we
    can all leave messages for each other and discuss strategy and levelling tips. I know there are
    templates available and I'm wondering if it would be just as easy to use one of the premade
    templates rather than create a site from scratch. Any comments would be greatly appreciated ....
  11. Website/blog Layout (circle Design)
    (2)
    Opinions? Took me a while, don't look at the design in the middle the abstract that is there
    just because i needed to put something there for a example. Judge the website layout it self. And
    if anyone wants to purchase this i'm open to offers.....
  12. Basic Of Website Creation
    Get basic knowledge on website creation here (1)
    By basic, i mean reaaaal "BASIC". I know that its probably redundant info for so many of us, but I
    still would like you to add your bit into this post , so that newbies benefit from it.....
  13. Website Layout?
    Help me please (3)
    Im sorta really new to html and php, and i want to make or edit a layout for my website that i might
    get from this forum thing, and i need sombody to point me to some tutorials or make me a layout.
    also if you want to you can make me a myspace one too xD. Please and thanks.....
  14. My Website Randomly Went Offline
    (8)
    My website was working fine, then when I tried to access it on Core FTP Lite (to upload files) Core
    FTP couldnt connect (i've changed my password, but forgot to change it on Core FTP). I
    disconnected from Core FTP to try and change my password, but then it couldn't re-connect, and
    my website has gone down. Everytime I try and go on, I get the "The page cannot be displayed. The
    page you are looking for is currently unavailable." page. However, it is only me who's getting
    this....and I can't log in using FTP or access the Cpanel Any help?....
  15. Creating A Good Website, How?!
    (18)
    Creating a good website, How?! I looked at many forums, searching on now to create a good
    website, by good I meant good website interface. For example, Trap17 have this amazing flash header,
    and nice design… I searched and searched, I found that many people started with a photoshop
    picture, then they make it come true by requesting a website coder (A.K.A. Programmer) to code the
    whole website for it. If, I said if, I were good a art, I can design a good nice picture off
    photoshop, and I know how to code, does that means I can make a good website? Please post any ....
  16. Flash Media Into Html/css Website
    does anyone know how to import a flash into a webpage with transparenc (1)
    Hi I need some help , Im designing this website for school studies However, I made a flash drop down
    menu, works perfectly, but you know how flash has a background when you export it in to a SWF file?
    For example my flash is width= 800, and height = 200 but my div box on my html page for my
    navigation is only 50 px my buttons is width of 50px and the rest of the content is the drop down
    animations i want to insert it into my navigation div box but i want to set the flash background to
    transparent so that when the drop down menu comes down it overlaps the text or whateva....
  17. I Am Looking Into Going With A Paid Hosting Service And Trap17 Has Been Good To Me So Whats The Paid Hosting's Website?
    (7)
    I am looking at different solutions for paid hosting and I know that that trap17 has some connection
    with a paid hosting company and I would like more info about it because I like the way this place is
    run and it has been a good place to have my website. So what is the site for the paid hosting?....
  18. I Need A Review On My Website
    Review me please (12)
    I need people to review the website i made for my dad. It was my dad's business's website.
    Tell me what you all think about it. Ive only been programming for a year so i think its good for
    only a year, but my opinion doesn't matter. So tell me what ya think. LINK ....
  19. Help! Php Or Just Html?
    i want to start buliding my website. which is better, php or basic htm (13)
    i try to start this topic in webhost category but it seems like i cant. i dont have the permission
    so i just post my topic here. im sorry mod.. i want to build a website which contains: - Links to
    videos - Informations - photos - flash i don't know if i should use php or just HTML. guys,
    what are your opinions..??....
  20. Php Scripts And Website Templates
    php scripts and website templates (6)
    I need some help. I´m trying to start my own website but I´m out of ideas about the design... The
    site should look something like this (click to view) Like I said I´m out of ideas so if any of you
    knows of a good and free web template that looks like my site please post the link to it. I´m also
    looking for some free php scripts (classified ads, fotolog, youtube, banner exchange, link exchange,
    adbux) so if you know where I can find any of those scripts please let me know. Thanks in advance.
    "I Need Some Help" isn't a good topic title. Changed to a more descript....
  21. Adding Your Website To Google
    How to register with google (20)
    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....
  22. How To Create Smallest Website
    (21)
    I wonder if any one create smallest website on earth? any webmaster can share this things .. .if
    they can make how could it be? /wink.gif" style="vertical-align:middle" emoid=";)" border="0"
    alt="wink.gif" />....
  23. What Are The Steps To Making A Website?
    (15)
    what are some steps to making a website? im doing a project and i need like 5-7, but id ont know
    waht to put. ....
  24. Runescape 2 Website
    (54)
    Can someone please give me a link to the runescape 2 website. I want to play runescape 2 but, I
    don't know the website and if you know the runescape 2 website then, please please please tell
    meeeeeeeeeeeeeeeeeeeeee. I tried to find the runescape 2 website everyday but, I didn't. I'm
    still searching for it, No answer yet. -Smartking790- ....
  25. Innovative Login System
    A new way to login to a website (17)
    Hi, I came across this website www.planmylifestyle.com which offers an innovative login system. In
    the traditional login system, a user is asked to enter a username and password besides many other
    personal information. In this website, to register the site creates an ID file that the user can
    download to the local hard drive. After registration, to login to the website, the user has to
    simply upload the registered ID file (browser and select ID file from local hard drive) and click on
    the Login Button. The user is then taken to the website which seems to be a searc....
  26. Excellent Free Website Templates
    (16)
    Site also includes 60 free logo templates, 63 free banner templates, 84 free newsletter templates,
    website arrows, abstract images, and much more. Fantastic resource...
    http://www.templatesbox.com/templates.htm ....
  27. 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 <style type="text/css"> <?php include ("st....
  28. Oldest Website?
    (37)
    Does anyone know of the oldest website on the internet that is still up? It would be kind of
    interesting to visit.....
  29. The Best And Free Website/html Editors + Text Editors
    A good collection! Check it out. (48)
    Here they are, the best html editors. Just pick one because they are all free, or choose one of the
    ones i most recommend. WebCore Designer 2005 http://www.mpsoftware.dk/webcoredesigner.php
    HTMLGate Free http://www.mpsoftware.dk/htmlgate.php Ma Page Web http://www.aldweb.com
    MAX's HTML Beauty++ 2004 http://www.htmlbeauty.com WebWorks http://w1.213.telia.com
    PageBuilder HTML Editor http://www.tafweb.com Website Mentor http://www.dark-street.com
    Cascade DTP http://www.price-media.demon.co.uk BPlainPro http://home5.swipnet.se/~w-52253/hy....
  30. The Most Annoying Website
    post the most annoying website you've encountered here (57)
    As you know, there are quite a few websites out there, some are professional while others are not so
    professional. This is where you come in. Have you ever been to a website where it was so bad that
    you had to use your hands to cover the annoying content? I know I had. This website that I visited
    today , in my opinion, tops the list in annoying websites. The links (and there are a lot of them)
    blinks. That's right, this author uses the tag so all links blink. Because of this technique,
    the majority of the site is very hard to read which is why I nominate http://....

    1. Looking for introduction, templating, templating, website, php

Searching Video's for introduction, templating, templating, website, php
Similar
Another
Boring New
Member
Introduction
- the title
says it all
I Cannot See
My Website
Or Log Into
Cpanel
Hi Everbody
- An
introduction
of my
personallity
...
I Can
&&
Cannot Acces
My Website -
Confusing
issue.
Need Help To
Increase The
Page Rank Of
Website!
Website
Optimization
Help
Introduction
Free Domains
For Bloggers
- My Website
Idea
Best Way To
Make Money
From Your
Website?
Has Anyone
Designed A
Website For
A Wow Guild?
Website/blog
Layout
(circle
Design)
Basic Of
Website
Creation -
Get basic
knowledge on
website
creation
here
Website
Layout? -
Help me
please
My Website
Randomly
Went Offline
Creating A
Good
Website,
How?!
Flash Media
Into
Html/css
Website -
does anyone
know how to
import a
flash into a
webpage with
transparenc
I Am Looking
Into Going
With A Paid
Hosting
Service And
Trap17 Has
Been Good To
Me So Whats
The Paid
Hosting'
s Website?
I Need A
Review On My
Website -
Review me
please
Help!
Php Or Just
Html? - i
want to
start
buliding my
website.
which is
better, php
or basic htm
Php Scripts
And Website
Templates -
php scripts
and website
templates
Adding Your
Website To
Google - How
to register
with google
How To
Create
Smallest
Website
What Are The
Steps To
Making A
Website?
Runescape 2
Website
Innovative
Login System
- A new way
to login to
a website
Excellent
Free Website
Templates
Changing
Background
Color In Php
- usefull
for
templating.
Oldest
Website?
The Best And
Free
Website/html
Editors +
Text Editors
- A good
collection&#
33; Check it
out.
The Most
Annoying
Website -
post the
most
annoying
website
you've
encountered
here
advertisement



Introduction To Templating - Templating your website with PHP



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE