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

UML Class Diagram

Here is a description of the different variables and functions:

Variables / FunctionsDescription
cssour css file for the template
isValidunused in this tutorial but might be useful once you get the hang of this to check if the template is valid based on whatever criteria you decide (file location invalid, something not defined etc)
templateDirthe path to and including the directory containing our template
TemplateDir()our constructor
display(file)the file to display in our template

Implementation

Let's 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 the 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 let's 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 let's 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 let's 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're not I am going to show you anyway 😛

Let's assume our PHP page is called mypage.php. The 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

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

$oTemplate = new Template();

Right, now we need to populate the variables on 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 are 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 separate the logic from your view and how to create nice clean models which allow for easy maintenance and being able to re-use content.

Rabid Dog out.

This page was published on It was last revised on

Contributing Authors

0

3 Comments

  • Votes
  • Oldest
  • Latest
SP
106 4
Commented
Updated

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

  • 0
    lol yeah, only way I can differentiate objects in PHP 😉 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 worthwhile. — Rabid Dog
add a comment
0
SF
25 0
Commented
Updated

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.

  • 0
    SpooF - I know you didn't ask me, but I'll give my two cents anyway. 😁 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 configurations 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 are 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. — UPSGuy
  • 0
    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 quite 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? — Rabid Dog
add a comment
0
SP
106 4
Commented
Updated
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.

  • 0
    It is quirky in PHP. I will do some tests for you so I can clarify it completely. — Rabid Dog
  • 0
    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 🤣) — Bogey
  • 0
    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? — Rabid Dog
  • 0
    Ah I see now. Sneaky. — spork
  • 0
    I thought there was a more technical reason 😱 — Bogey
  • 0
    Well it is technical. Remove the assignment of $this to the $template variable and see what happens 😉 — Rabid Dog
add a comment
0