The Logic Behind Template Engines (PHP-Based)

Posted: June 26, 2010 in PHP5, PHP5.3

Why use Smarty? why use Twig? why use TinyButStrong? PHP is a ‘Template Engine’?

We use it to ‘separate PHP from HTML‘, .. or was it to ‘separate business logic and presentation logic‘ .. or .. was it because ‘I’m lazy‘ .. or maybe .. just maybe .. I’m using it because ‘everyone else is using it’.

It doesn’t matter which one you use or for which reasons you use it, as long as you understand the logic of why you use a template engine.

  • A pink wooden car ..

Let’s start with the usual non-technical example, a car. You want to build a car and of course the first thing you do is design it. So you take a paper and pencil and start drawing your car. When it’s finished, you give your paper with the car design over to some folks at some car-building-company who know how to build cars. The car-building-company only know from the design how it is going to look, they only have your paper with the design, nothing more. These folks can decide what becomes what; will it be made of steel or fiberglass, what color it should have, etc.

You don’t want the car-building-company to decide what the car would be made of, after all, you don’t want a little pink wooden car returned that has the size of a tennis ball. So before you handed over the paper, you wrote a few separate papers with explanations and examples of what everything should look like; dimensions, material, color, wheels, etc. You write them on separate papers because you don’t want to spoil your design in case you changed your mind on some details (maybe the color red is better? or maybe orange?).

A template is nothing more than a blueprint, a design. The template pattern proposed by the Gang Of Four (you really should get to know them) is an example of what a template stands for. In reality, a template doesn’t exist, but something that might exist (in different versions) in terms of the template.

Let’s make a code example:

// An abstract object, a template (also called, a blueprint).
// -
// If you inherit me, I demand that ...
abstract class Template {
  // .. this method is public, called __construct, has no parameters
  abstract public function __construct() {  }
  // .. this method is public, and called one, has no parameters
  abstract public function one() { }
  // .. this method is public, and called two, has no parameters
  abstract public function two() { }

// Template inheritance
class ThisClass extends Template {
  // As demanded by Template, I have to make this method public, call it one, and assign no parameters ..
  public function one() {
    // .. but I can write here whatever I want
  // Rest of methods Template demands to implement (__construct(), two())

// Second template inheritance
class ThisClassAlso extends Template {
  // As demanded by Template, I have to make this method public, call it one, and assign no parameters ..
  public function one() {
    // .. but again, I can write here whatever I want completely independent of ThisClass ..
  // Rest of methods Template demands to implement (__construct(), two())

The template does not care what the code of these methods will be, it only cares about the design. What the initial code of ThisClass and ThisClassAlso methods will be is entirely up to you and your goal of this design. You can be certain of a few things when working with template designs:

  • The initial design is known.
  • The initial implementation of the design is unknown.
  • A template does not care about the implementation, it only cares about its design
  • Every implemented design knows each others initial design when they inherit the same template.

This might sound very stupid or very complicated, but it’s very simple. The initial design are the template demands. The implementation is the code (logic) each method implements. Each implementation (ThisClass, ThisClassAlso) of the template (Template class) knows each others initial design (our 3 methods) because they inherit the same template (Template class).

We can verify this statement with a simple example:

// 1* PHP-Based, e.g. in Java you can set a method return type for returned values.
// First implementation of Template.
class ThisClass extends Template {
  public function __construct() { }
  public function one() { return "one "; } // logic, returns string 'one'
  public function two() { return 1; }        // logic, returns int 1

// Second implementation of template.
class ThisClassAlso extends Template {
  public function __construct() { }

  public function one() {
    // I can create ThisClass without parameters, because I know the design
    $thisClass = new ThisClass;
    // (1*) I do not know what ThisClass::one() and ::two() return, but I return a string ..
    return (string)
       $thisClass->one().  // .. I know this method exists, I know the design ..
       $thisClass->two();  // .. and this one too ;)

  public function two() { return '2'; } // logic, returns string '2';

1* – It doesn’t matter if PHP fully supports every principle of OOP. In Java you can explicitly program what each method returns (method return type), therefor you can strengthen the template demands. In PHP however, every method declared in a class is automatically a void. PHP does not throw a compile error when a method doesn’t return something (which is always null) where Java would throw a compile error -.

You may think; “What’s so wonderful about these examples, I write these every single day”, well if you do, then you know now you have been using template concepts every single day.

I’ll assume you thus far understand the logic of a template.

  • The Template Engine

If you searched the net for topics like ‘PHP Template Engines, PHP is a template engine, Why use a template engine, PHP template engines are useless’, you will discover that almost every post on a forum or a blog turns into a discussion poul. The arguments (or principles) used in these discussions are pretty mixed up. Well the explenation for this mix up is very simple.

There are in general three types of people using templates; a programmer, a designer and one that is both.

Arguments used for programmers is to separate the “data logic” (“Business Logic”) from the “presentation logic”. Most likely the programmers want to separate peaces of code in different categories:

  • One category would be the setup of your environment (file inclusions, database connection, objects to be created).
  • Second category would be the flow of data retrieval and forward sends.
  • The last category would be that of the designer, present this flow in a more readable form.

This separation makes it possible that the programmer and designer can work simultaneously on the same project. When these categories get mixed in one file, the designer and programmer have to work with different logics on the same files. You can think up the rest what kind of mess this can become.
Another argument is time. A lot of programmers are lazy and use template engines for the short syntax. They are tired of the <?php echo $somevar; ?> syntax. Some template engines come with a very short syntax functionality which saves time and mixes HTML faster and easier with the template syntax. This is a very important argument for a programmer to work with a template engine and defend it against any criticism. They will rarely use this argument (which is of course legit).

Arguments used for designers (non-programmer) is to separate the PHP code from HTML and vica versa. This makes of course sense; a typical template designer does not (or does not like, understand or want to) progam. They design most likely in a markup language (HTML, CSS, etc). Here we come to the point that template engines have become what they are now. Designers argue with the fact “We don’t know how to design (program) in PHP”. In fact, this statement should be “I have not learned how to design (program) in PHP, but we still want the functionality present in the native language (PHP) to work with”. And therefor, step by step, a second syntax is created on top of the native syntax which actually converts the native synax in shorter, easier peaces of code, where you get this feeling as a programmer that these were made for designers.

The arguments for designers became more present in the discussions of “Template Engines”. You can believe me when I say, that there is no designer I’ve worked with that didn’t understand any of PHP. It is more likely to assume that most designers started programming with PHP like any other programmer once started with a certain language.

Just recently, I stumbled upon‘s blog. He posted a small statement on PHP template engines and why they are useless. Skrol29 commented on this post, and I quote:

Well, of course I cannot agree with your assertion. (I’m a coder of the TinyButStrong Template Engine)
You say “I’ve never had to do anything in my HTML that couldn’t be done with PHP”. But the point of template engines is not to do things in the HTML, but to not do HTML in the PHP, and (as possible can be) to not do PHP in the HTML template.

Smarty doesn’t succeed really in the second point because its tag syntax is made very closed to the PHP syntax in order to be easily turned (they say “compiled”) into PHP.

Therefore, coding Smarty templates is sometimes very closed to coding PHP, as you have underlined it.

Nevertheless, as soon as the purpose is an human interface, the coding language naturally needs a template engine philosophy. PHP is not a template engine that enables us to have a pure PHP script and a pure HTML template that can be both designed with appropriate editors.

What lot of template engines are missing is templates that should be editable in all WYSIWYG/Visual Editors.

He is a ‘coder’ (maybe he means programmer) of the TinyButStrong template engine but uses the arguments of a designer. Which of course, you should know by now, is confusing and does not really make any sense for a programmer. So you would guess he is a designer and codes templates. Or maybe he is a programmer and uses the arguments of a designer .. confusing .. I know. The comment of Skrol29 are comments that can be found in major quantities on every forum or blog discussing this topic.

The two points of Skrol29:

  • to not do HTML in the PHP
  • not do PHP in the HTML template

Second, Skrol29 says that Smarty does not do a great job in his second point (and prolly all template engines for that matter), because the Smarty syntax and the PHP syntax would be too similar. This eventually means that mixing Smarty syntax with HTML is the same as mixing PHP syntax with HTML. Although this argument is interesting, it crushes his own statement while defending template engines (TinyButStrong in particular). So I’ll leave this as it is.

Third and last, a human interface needs a template engine philosophy, therefor PHP is not a template engine because it cannot create separate pure PHP scripts and pure HTML scripts. Again, very interesting, but to practically realize this statement, HTML has to be redesigned in order to create a true separation between PHP and HTML. If this separation would be possible, it would make the use of PHP obsolete.

I will use two argument in particular that is most used when discussing ‘Template Engine’ topics, separate PHP from HTML (1) and HTML from PHP (2). Both arguments seem similar, they are different.

  • What is PHP, what is HTML ..:

To separate PHP from HTML and of course HTML from PHP, we first have to define why in the first place we are using HTML and PHP. We will define it by asking two questions; what is it? and why do we use it?.

  • What is it?
  • PHP is our back end, our server side scripting language. It is dynamic.
  • HTML is our interpretation language for browsers, a markup language. This means our visitors (audience, clients) will have to use a browser (or any other HTML interpretor) to access our medium. HTML will be interpretated on the client side. It is static

  • Why do we use it?
  • We use PHP to make HTML dynamic. Here we have abilities to access a database and other cool stuff that enriches HTML’s dynamic-ness (that word doesn’t exist, I know ..)
  • We use HTML because this became a standard component for every browser interpretation. Majority of browsers created after 2004 fully support HTML 4.0. It has a very easy syntax (tag code) and is very well suited in combination with other languages like CSS and Javascript to make information more presentable to the eye.

So we have defined PHP and HTML and for what purpose we use each of them. Now we can separate them.

  • Separate PHP from HTML and HTML from PHP

What people actually mean by this statement is the style of how PHP with HTML (and vice versa) can get mixed (and you will see this type of mixture in ALL ‘beginners’ tutorials on every PHP site), best explained with an example:

// some database connection
// fetching associative array
$result = $pdo->query("SELECT * FROM table");

$str = '<ul>';
foreach($result as $row) {
  $str .= "<li>{$row['name']}</li>";
$str .= "</ul>";
echo $str;

This example is used in situations where the programmer is also the designer (and vice versa). Here separate programmers and designers cannot work very well together simultaneously. If they do, version control and file updates will become very difficult, if not impossible. Most important argument of all, we assume a designer does not understand a programming language. Therefor the designer is unable to work in the environment of a programmer.

So we separate the HTML tags that get mixed with the PHP code and use a template concept.

// separate file: data-logic.php
$result = $pdo->query("SELECT * FROM table");
include "presentation-logic.php";

// separte file: presentation-logic.php
<?php foreach($result as $row): ?>

   <li> <?php echo $row['name']; ?> </li>

<?php endforeach; ?>

Presentation files can be replaced without a programmers fear of updated code that will be overwritten and get lost. Although an environment is created where programmers and designers can ‘sort of’ work independently from each other, we still have to assume that the designer does not know how to use any PHP language structure. So we replace the PHP code with a template syntax that designers apparently do understand:

// separate file: data-logic.php
$result = $pdo->query("SELECT * FROM table");
$engine = new Engine;
$engine->assign('result', $result);

// separate file: presentation-logic.tpl
 {foreach $row in $results}

   <li> {$} </li<


Now we have successfully replaced our PHP code with that of the template syntax. We can now practically say that the PHP code is separated from the HTML and vice versa. The programmer has its own file in its own language to work with, so does the designer.

But does this make sense at all? Replacing the PHP syntax with another syntax that from appearance, looks different, but from functionality is exactly the same? Not to mention that the whole point of using PHP was to make HTML more dynamic. Therefor separating PHP from HTML as in the arguments of “You should not use PHP code in your HTML” does not make sense at all.

In other words, a designer does understand and knows how to use this:

{for $items as $item}
// - template syntax
{foreach $item in $items}

But does not know how to use this:

// - php syntax
foreach($items as $item)
  • So my conclusion.

Does replacing the syntax with the native one ‘separate PHP code from HTML’, Technically no, Practically yes.

But what do we achieve by replacing a template syntax with that of the native one. Instead of using the PHP syntax, we now use a complete different one. We achieved nothing.

Does a template engine need to be separated from its native syntax in order to function as a template engine? No.

Does separating the PHP code from HTML have anything to do with the functionality of a template engine? No.

Why do we use this argument in template engine discussions? Because we assume a designer cannot handle PHP’s (complex) syntax, only a (complex) template syntax.

  1. galen says:

    ive since moved all my code over to smarty

    just kidding.

  2. Andrey says:

    Why do we use this argument in template engine discussions? Because we assume a designer cannot handle PHP’s (complex) syntax, only a (complex) template syntax.

    Template engines limits developers. They allows to write less pure code then in case of native PHP. It is a fact that developer can put in PHP-template everything even business logic ant it is not acceptable. But template engines do not allows that. Also, template engines has tools for filtering and data manipulating. It is useful.

    Really I don’t very like template engines. But I use them. Smarty for example… However if you would like you can take a look at my own template engine named Aste:

    Good luck!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s