PHP Templates and why they will change your life.

Published on August 1st, 2007 by admin

Templates are what separate the beginners from the pros. Learn how to build a basic template system here!

What you will need

  • A server with php installed.
  • A pure text editor. I like Notepad++.

The Source

Download the PHP Template Source Code

Part One: What is a template system?.

So exactly what is a template? Well according to the American Heritage dictionary, a template is . . .
“A document or file having a preset format, used as a starting point for a particular application so that the format does not have to be recreated each time it is used.”

You know what? They’re just about right!

So basically, a template system separates your HTML from your PHP. Let me say that again. A TEMPLATE SYSTEM SEPARATES YOUR HTML FROM YOUR PHP!

Imagine the implications of this. You no longer have to use includes to add content to your website. You can
create different skins and let the visitor choose what they want. You can generate lists and never
have to write HTML like this . . .

$html = "
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>";

The possibilities are endless!

There is no better way to learn about template systems then to create your own so let’s get started!

Part Two: Building your own template system.

If you’ve read my other php tutorials, you probably have seen the code can be rather complex. Well I’ve got
good news for you. . . this code is EXTREMELY easy.

Here is the concept behind how it works.

  • Open a file and save the contents into a string.
  • Replace a string pattern (such as {VAR}) with a value.
  • Output it.

There are only 81 lines of code for this script (and half of that is comments so get ready :)).

Create a new file and name it template.php

Copy and paste the following code into template.php please refer to the comments for explanation.

Note: If you have never used Object Oriented Programming before I encourage you to read up on it
and then come back. You can find a good tutorial here

class template
{
/*********************************************************************
VARIABLES
Setting our variables
*********************************************************************/
var $template; 			//The template name
var $template_string;    	//The template string will be stored here
var $prefix    = "{"; 		//The variable prefix character.
var $suffix    = "}"; 		//The variable suffix character.
var $var_array = array(); 	//The values of your variables will be stored here

/*********************************************************************
SET TEMPLATE
This function sets the file that we are going to be grabbing our
html from
*********************************************************************/
function set_template($filename)
{
$this->template = $filename;
}
/*********************************************************************
SET VARS
This function sets a value for a variable
*********************************************************************/
function set_var($name, $value)
{
//storing our variable and its value into an array
$this->var_array[$name] = $value;
}
/*********************************************************************
LOAD FILE
This function loads the contents of the template
file into a string.
*********************************************************************/
function load_file()
{
//saving its contents into a string
$this->template_string = file_get_contents($this->template);
}
/*********************************************************************
REPLACE VARS
This function replaces the variables with
it's corresponding values
*********************************************************************/
function replace_vars()
{
//The foreach loop is very useful when we want to loop through
//associative arrays.
foreach($this->var_array as $assoc => $value)
{
//appending the variable prefixes to match. ex: {VAR_NAME}
$var_name = $this->prefix.$assoc.$this->suffix;

//replacing every instance of the variable with it's corresponding value.
//so {VAR_NAME} becomes "this is my variable"
$this->template_string = str_replace($var_name, $value, $this->template_string);
}
}
/*********************************************************************
PARSE
This function calls the actions and outputs the
final result.
*********************************************************************/
function parse()
{
//loading the file
$this->load_file();

//setting the variables
$this->replace_vars();

//outputting the newly parsed template :)
return $this->template_string;
}
}//end of class

And that’s our whole template class!

Part Three: Using your new template class.

Ok. . . your new template class is done and ready to go. . . but how do you use it? By itself the class doesn’t seem all that remarkable. But trust me, it is.

To demonstrate we’re going to create a basic personal profile page.

Create a new file and name it interface.htm copy and paste the following code into interface.htm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>{PAGE_TITLE}</title>
</head>
<body>
<div style = "margin:auto; width:800px; height:600px; border:solid 1px #808080">
<div style = "height:70px; background:#c6c6c6; padding:5px">
{PAGE_TITLE}
</div>
<div style = "padding:5px">{CONTENT}</div>

</body>
</html>

Do you notice {PAGE_TITLE} and {CONTENT}? Guess what. . . .those are variables! That’s right! With a template systemyou can embed variables right into HTML! Are you starting see what I’m getting at? :)

Open up interface.htm in a browser, it should look something like this.

Screenshot of File

Create a new php file and name it index.php, save it in the same directory astemplate.php.

Take a look at the code below.

//This loads template.php into memory
//(you can also use include, they both do the same thing)
require_once("template.php");

/*******************************************
INTERFACE
*******************************************/
//creating a new instance of our template class
$interface = new template;

//setting the template file that I want to grab html from
$interface->set_template("interface.htm");

//outputting the interface
print $interface->parse(); 

Open up index.php in your browser. See any difference? You shouldn’t. Take a look at the source code, it’s
exactly the same as template.htm You’re grabbing the content inside template.htm, saving it as a string
and then printing it.

Ok let’s make one more template.

Make a new file and name it profile.htm Copy and paste the following code into your new file.

<div style = "margin-bottom:10px">
This is the profile for {NAME}
</div>

<table width = "100%">
<tr>
<td>
<img src = "{PROFILE_PIC}" />
</td>
<td>
Name:{NAME}
<br />Birthday: {BIRTHDAY}
<br />Phone: {PHONE}
<br />E-Email:{EMAIL}
<br />Bio: {BIO}
</td>
</table>

Notice the omission of the html, head and body tags.

Open up profile.htm in your browser, it should look something like this.

Screen Shot of Template Profile

Grab any image you like and name it pic.jpg save it in the same directory.

Your directory should look like this.

Screenshot of folders

Note: Given the nature of operating systems your icons may not resemble mine.

All right, let’s put these two templates together.

Open up index.php again and right above where you created a new instance of your interface class write this code.

/*******************************************
PROFILE
*******************************************/
$profile = new template;
$profile->set_template("profile.htm");

//setting the variable values
$profile->set_var('PROFILE_PIC', "pic.jpg");
$profile->set_var('NAME',        "Josh");
$profile->set_var('BIRTHDAY',    "08/03/1985");
$profile->set_var('EMAIL',       "joshua.bolduc@gmail.com");
$profile->set_var('PHONE',       "555-555-3452");
$profile->set_var('BIO', 	 "This is some kind of dynamically generated bio");

//compiling the information and saving the string into a variable
$content    = $profile->parse();

//setting the page title
$page_title = "Personal Profile";

index.php should look like this.

//This loads template.php into memory (you can also use include, they both do the same thing)
require_once("template.php");

/*******************************************
PROFILE
*******************************************/
$profile = new template;
$profile->set_template("profile.htm");

//setting the variable values
$profile->set_var('PROFILE_PIC', "pic.jpg");
$profile->set_var('NAME',        "Josh");
$profile->set_var('BIRTHDAY',    "08/03/1985");
$profile->set_var('EMAIL',       "joshua.bolduc@gmail.com");
$profile->set_var('PHONE',       "555-555-3452");
$profile->set_var('BIO', 	 "This is some kind of dynamically generated bio");

//compiling the information and saving the string into a variable
//see where this variable goes in the $interface template?
$content    = $profile->parse();

//setting the page title
//see where this variable goes in the $interface template?
$page_title = "Personal Profile";

/*******************************************
INTERFACE
*******************************************/
//creating a new instance of our template class
$interface = new template;

//setting the template file that I want to grab html from
$interface->set_template("interface.htm");

//setting the variables for the interface
$interface->set_var('CONTENT',    $content);
$interface->set_var('PAGE_TITLE', $page_title);

//outputting the interface
print $interface->parse();

Do you notice above I’m not actually doing a lot of “coding?”. I’m just setting values and then outputting. Nothing

could be easier!

Open up index.php in your browser, it should look like something like this.

17_004

So do you see the advantages of this technique? By keeping the interface separate from the content (such as the profile) we can make one change to the interface and it will change for everything! no need to touch any other files. That’s what makes skinning possible!

Conclusion

Templates open up a whole new world of possibilities in php. Learn it well!

I hope this was helpful, if you have any questions or suggestions feel free post in my comments.

Leave a Reply




Comments

  • Post by RicardoC on August 20, 2007

    Great Tutorial.. Again ! :)

  • Post by Christian on August 30, 2007

    very nice Tutorial..

  • Post by Red Mantis on September 3, 2007

    Thanks you so much, this was worth learning. Keep it up man.

  • Post by rocoso on September 28, 2007

    coool good looking out

  • Post by papaman on October 4, 2007

    nice tutorial but there is already a script that does exactly that.smarty.php.net

  • Post by matthew on November 6, 2007

    I am using basically exactly the same method on a project, its a powerful concept. However, you should consider using PHP's *printf() functions instead of str_replace() for replacing the variables where speed is an issue...

  • Post by CarlMiami on November 6, 2007

    Very good tutorial. As someone pointed out, of course there is Smarty and others but knowing how to write our own helps much more than just using a tool. Thanks again.

  • Post by jay on November 14, 2007

    great tutorial. as others have pointed out, there is Smarty , but for small projects this will do just fine. Thnx

  • Post by Anders on December 20, 2007

    Really nice tutorial (just as the rest of your tuts). I'm going to integrate something like this.Thanks!

  • Post by Lori on December 31, 2007

    Great tutorial for beginners!

  • Post by limbu on June 16, 2008

    Hello can you help me with looping certain part in the template. Let's say i want to display the list of members from my database. How can i do it using this template class. Please help you can email me or I will watch this blog again. thanks

  • Post by Rick White on September 1, 2008

    Great article. You forgot to include the page_title variable in the HTML code.

  • Post by Noob on December 30, 2008

    Yeah mate. This is awesome. Keep going.

  • Post by firefly on January 5, 2009

    great tutorial! is there a way to use php include in the interface.html file if i change it to interface.php? it didn't work when i tried it. just want to consolidate code across multiple sections of the website.

  • Post by chris i. on February 8, 2009

    what it takes to do a template script like hi5? for a biginer where do i start,,thank you

  • Post by mark on April 2, 2009

    hi joshua thanks so much for this, it's very informative, and very well explained. thanks!

  • Post by syed ahmed irfan on April 17, 2009

    Hi this is irfan here i have completed my B.COM(computers). and i have done php course outside so i need a help from you. can you send me a mail regarding creating php template in a video format. thank Q

  • Post by wiphone on May 6, 2009

    Great template, it has become much easier with your tips

  • Post by zulubanshee on May 11, 2009

    I cut and pasted everything exactly as it is and it doesn't work at all.

  • Post by Joshua Bolduc on May 11, 2009

    Did you try the source code at the top?

  • Post by Sanjai on June 5, 2009

    zulubanshee.. Paste them inside PHP Braces:

  • Post by yor on June 15, 2009

    Aha great tutorial. I've been doing somthing to that extent with javascript but its really limiting so I am slowly floating towards php. Only one problem I am wonder of...Is it best to save the body in a xml or a regular txt file...I mean which way is more common for storing web data.

  • Post by Joshua Bolduc on June 15, 2009

    Best practice is to retrieve data as xml or json. You may also retrieve it as html. If you're using javascript then I suggest you try jQuery (if you're not already) it'll make things much easier for you.

  • Post by yor on June 16, 2009

    Thanks for the tips, jQuery seems amazing.Gonna definitely be working with it in the near future. Only problem I am left with in web design is implementing ajax and dynamic urls. (ajax tutorials are a common place) but not so for dynamic urls...maybe one day a tutorial could be made ;P...Just wondering.

  • Post by PCWorkspace on May 18, 2010

    Copied and pasted but didn't work for me - simply published the code to screen - installed your source code, worked fine - thank you for all your hard work.

Popular Posts

Posts By Category

Supported by