Using Templates with PHP - dummies

By Andy Harris

As web development becomes standardized, the Model-View-Controller (MVC) architecture has become more popular. The basic idea of this mechanism is to separate the data elements (the model), the user interface (the view), and the code that connects the model and the view (the controller).

Many programming instructors emphasize separating content, layout, and data. However, the way PHP is often written, it combines all three elements. As a response, web developers often use some form of templating system to try to separate the content from the view.

The simplest form of a template is something like the following code:

<?php include_once("vars.php") ?>
<!doctype html>
<html lang="en">
  <meta charset="UTF-8">
  <div id = "main">
  <div id = "footer">

The page holds the structure, but none of the actual contents. The contents are stored in PHP variables, which are stored in another file, called (in this example) vars.php. Here’s what vars.php might look like:

$title = "template demo";
$heading = "Template Demo";
$content = <<<HERE
This is a very simple template example, which allows the user to load
content as variables from an external file. Of course, template
systems get much more complex than this.
$footer = "from HTML5 / CSS All in One for Dummies";

In this extremely simple example, the second PHP file simply defines variables containing the various values, achieving separation of data from view. Often, the secondary PHP file is more sophisticated, grabbing contents from a database or other storage medium.

Note that <?=$varname?> is a shortcut mechanism commonly used in templating situations. It opens PHP, prints the value associated with the variable name, and then quickly returns to HTML. When PHP is used for templating, you frequently pop in and out of PHP.

Of course, a number of template engines today add a great deal more to templating. One of the more prominent is Twig.

Twig takes a template written in a special simplified format and compiles it to PHP, allowing you to write sites like this (example from the Twig documentation):

<!DOCTYPE html>
        <title>My Webpage</title>
        <ul id="navigation">
        {% for item in navigation %}
            <li><a href="{{ item.href }}">{{ item.caption }}</a></li>
        {% endfor %}
        <h1>My Webpage</h1>
        {{ a_variable }}

Twig allows you to use a PHP-like syntax to create powerful templates. It also includes features for populating the variables that help to separate the data from the presentation and the control.

A number of other popular template engines include Smarty and Savant.