Basic PHP Templating mechanism

Having seen many embedded HTML strings in PHP functions I thought it would be helpful to illustrate a really simple straight forward way of implementing a templating engine. This tutorial is broken into 4 sections namely
1) Requirements
2) System Design (UML)
3) Implementation
4) Usage of implementation

Requirements

1) Fully functional HTTP server including PHP binaries for that server
2) Text Editor
3) Web browser capable of rendering the content

System Design

Description:
css = our css file for the template
isValid = unused in this tutorial but might be useful once you get the hang of this to check if the template is valid based on what ever criteria you decide (file location invalid, something not define etc etc)
templateDir = the path to and including the directory containg our template
TemplateDir() = our constructor
display(file) = the file to display in our template

Implementation

Lets define our constructor

 
 
function Template(){
  $this->templateDir = "default";
  $this->css = "default.css";
}
 

Here we define the template dir as "default" which means this, if you are working on file home/mypage.php and including the template file from there, the path to the directory containing th info will be home/default/. So in other words the folder will be relative to the path of the calling file. Next we define the stylesheet as default.css which means the path is home/default/default.css. Understand? Great lets move on then

 
function display($file){
  $template = $this;
  error_reporting(E_ALL);
  include_once("template/" . $this->templateDir ."/".$file);
}
 

Here we set the error reporting level, you might at a later stage want to define some sort of flag that changes the reporting level to suit the environment, like production or development instance. then we include the file according to the directory we specified in the constructor. this path has template prefixing it as I prefer to store my templates in a directory called templates (funny that). So the path would be home/templates/default.

The class in all its glory below

 
<?php
 
class Template{
 
  var $templateDir;
  var $css;
  var $isValid;
 
  function Template(){
    $this->templateDir  = "default";
    $this->css = "default.css";
  }
  function display($file){
    $template = $this;
    error_reporting(E_ALL);
    include_once("template/" . $this->templateDir ."/".$file);
  }
}
 
?>
 

Right everyone with me so far? Great lets define some templates

header.tpl (inside the default folder)

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>My Template :: <?php echo $template->title; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="template/<?php echo $template->templateDir . "/default.css" ?>" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
My Template header <?php echo $template->welcome; ?>
</div>
 

There we go, save the file and lets proceed to home.tpl in the same directory

 
<div>
Well hello there <?php echo $template->name; ?><br />
I am so glad you could join me on my <?php echo $template->content; ?><br />
Look here, I have put your name in a textbox <input type='text' id="txtMyName" value="<?php echo $template->name; ?>" /><br />
have a happy day!
</div>
</body>
 

Cool so now our implementation is done! I have included the text box so you can see that this can be used in data entry forms when editing data.

Usage

Well I bet you itching to see this right? well even if you not I am going to show you anyway 😛

Lets assume our PHP page is called mypage.php.

First thing we do is include the template class

 
include_once("lib/Template.class.php") // I have saved the template class we added into a dir called lib as file name Template.class.php
 

Next thing we do is create a reference to the Template object (for those that have worked with classes the correct term is instantiate an instance Template class)

 
$oTemplate = new Template();
 

Right, now we need to populate the variables in the page

 
$oTemplate->title = "Check out my template page!";
$oTemplate->welcome = "Howdy doody!";
$oTemplate->name = "Captain Cheese Monkey";
$oTemplate->content = "Here I can put all my html content, whether it be a read from a file or dynamically created content from my super DB";
 

And we all done! Here is the complete page
mypage.php

 
<?php
include_once("lib/Template.class.php");
 
$oTemplate->title = "Check out my template page!";
$oTemplate->welcome = "Howdy doody!";
$oTemplate->name = "Captain Cheese Monkey";
$oTemplate->content = "Here I can put all my html content, whether it be a read from a file or dynamically created content from my super DB";
 
$oTemplate->display("header.tpl");
$oTemplate->display("home.tpl");
?>
 

And that as they say in the classics is that. Nice clean and simple. You can extend this from here to the four corners of the planet (it is flat right?) and enjoy time doing the fun things like coding logic as opposed to coding HTML strings!

Conclusion

This is an extremely simple example designed to get you up and running fast. This is by no means a comprehensive solution but is aimed at helping you understand how to seperate the logic from your view and how to create nice clean models which allow for easy maintenance and content reusage.

Rabid Dog out.

This page was published on

0

13 Comments

  • Votes
  • Oldest
  • Latest
SP

Fee fye foh fum... I see Hungarian notation in there!

add a comment
0
RD

lol yeah only way I can differentiate objects in PHP 😉

add a comment
0
RD

Fee fye foh fum... I see Hungarian notation in there!

Besides in a duck typed language it is the only way to clearly see what the object is LOL. I do however appreciate the fact that you picked it up, had a good chuckle when I read your comment. Made the tutorial worth while.

add a comment
0
SF

Rabid Dog, whats your take on systems like smarty? When should they be used? I've been in a lot of discussion over systems like smarty and something simple like what you have here.

add a comment
0
UG

SpooF - I know you didn't ask me, but I'll give my two cents anyways. 😁 I've built a half-dozen or so projects using Smarty & I've spent the last year or so of my career customizing three separate installations of SugarCRM, which also implements Smarty.

IMHO, the Smarty engine is great for large applications where a cache may come in handy. Our CRM systems get hit several hundred times an hour, serving up a large header and menu with each hit, so the caching is a benefit for us. I also like the external configuration files that you can implement. If you need to migrate between dev/QA/prod environments or between systems, then having all your configuration in one place is a great way to smooth transitions. Those stand out in my mind as the features I most use in Smarty, but there's also a few that I've used here and there when necessary such as filtering and template functions. Of course, compiled templates are always a benefit, too.

All that being said, there's a place for sweet and simple, too. A templating system like what Rabid Dog has provided would definitely be my choice over Smarty for smaller projects. Smarty performs surprisingly well given all of its capabilities, but it can also overwhelm a project.

add a comment
0
RD

Rabid Dog, whats your take on systems like smarty? When should they be used? I've been in a lot of discussion over systems like smarty and something simple like what you have here.

My opinion on smarty is this.

It is a created framework so it probably contains a great deal of useful stuff. The only thing I have against it is just that, it is a framework with a lot of stuff in it 🙂

This simple templating solution has allowed me to create a number of sites and works quiet nicely. The other thing is the learning curve. This you write it so you can extend it as needed. So only when you need the extensions put them in, not before 🙂

Again I must stress I have nothing against smarty but prefer the absolute control I get out of writing my own 🙂

Make sense?

add a comment
0
SP
function display($file){
  $template = $this;
  error_reporting(E_ALL);
  include_once("template/" . $this->TemplateDir ."/".$file);
}

What purpose does the blue line above serve? It looks like all you're doing is creating a copy of your self reference but not using it.

add a comment
0
RD

It is a quirky in PHP.

I will do some tests for you so I can clarify it completely

add a comment
0
BO
function display($file){
  $template = $this;
  error_reporting(E_ALL);
  include_once("template/" . $this->TemplateDir ."/".$file);
}

What purpose does the blue line above serve? It looks like all you're doing is creating a copy of your self reference but not using it.

He is using it... look at the HTML part of the template example... I actually understand half of it... (The 'what for' part... not the why 🤣 )

add a comment
0
RD

Yes spot on 🙂 the $template variable is available when called inside the template (.tpl) page. As to why? Well when the file is included it is included in the context of the function therefore the $template variable is available inside the included page 🙂 Allowing you to assign values to it via the $oTemplate variable.

Make sense?

add a comment
0
SP

Ah I see now. Sneaky.

add a comment
0
BO

Yes spot on 🙂 the $template variable is available when called inside the template (.tpl) page. As to why? Well when the file is included it is included in the context of the function therefore the $template variable is available inside the included page 🙂 Allowing you to assign values to it via the $oTemplate variable.

Make sense?

I thought there was a more technical reason 😱

add a comment
0
RD

Well it is technical. Remove the assignment of $this to the $template variable and see what happens 😉

add a comment
0