PHP

PHP Template Engines

A PHP template engine is a way of outputting PHP in your HTML, without using PHP syntax or PHP tags. It's suppose to be used by having a PHP class that will send your HTML the variables you want to display and the HTML will simply display this data. This means that you are forced to separate your PHP logic with the HTML output, which is great, separation in your code is what you should be aiming for.

The best way to understand what a template engine does it to see the code. Below is a basic page where you might want to display a title and a list of products.

<?php
    $title = 'Product Page';
    $products = $productModal->getAllProducts();
?>
<h1><?php echo $title; ?></h1>

<div class="products">
    <?php
        if(empty($products))
        {
            echo 'No products exist';
        } else {
            foreach($products as $product)
            {
                ?>
                    <h2><?php echo $product->title; ?></h2>
                    <p><?php echo $product->description; ?></p>
                <?php
            }
        }
    ?>
</div>

The idea of using a template engine is that you would remove the $title variable and the $products variable and put this in a class and then call a template file to display the HTML.

<?php

class Display_Products
{
    public function indexAction()
    {
        $vars = array();

        $vars['title'] = 'Products';
        $vars['products'] = $productModal->getAllProducts();

        $this->renderHtml('all-products.html', $vars);
    }
}
?>

The renderHtml() method will pass in the variables you want to display to the template file which will look similar to this.

<h1>{{ title }}</h1>

<div class="products">
    {% for product in products %}
        <h2>{{ product.title }}</h2>
        <p>{{ product.description }}</p>
    {% else %}
        No products exist.
    {% endfor %}
</div>

As you can see there is a separation of the PHP logic and displaying the code. Another reason why you might use a template engine is because now you have a HTML view file which you can give to your front-end developer and they can style this HTML, a template engine is arguably easier to read than using PHP syntax.

What Frameworks Currently Use Template Engines?

There are a few large frameworks that currently use a template engine some of the ones I've used are Laravel, Drupal 8, Expression Engine. All of these use different template engines but the understanding of how they work is similar.

Laravel - Blade Templating

Code Happy - Blade Templates

Laravel uses a template engine called Blade, here is an example of how you will use blade in your HTML views.

<!-- Stored in app/views/layouts/master.blade.php -->

<html>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

Output A Variable

{{ $val }}

Foreach Loop

@foreach ($users as $user)
 <div class="user">{{ $user->name }}</div>
@endforeach

If/else Statement

@if ($user->name == 'Dave')
 <p>Welcome Dave!</p>
@else
 <p>Welcome Guest!</p>
@endif

Blade Templating

Drupal - Twig

Homepage - Twig - The flexible, fast, and secure PHP template engine

The Drupal CMS uses a template engine called Twig, this was developed to make templating quicker and more secure. It works in a similar way as blade but the syntax is slightly different.

Output A Variable

{{ var }}

For Loop

{% for user in users %}
    * {{ user.name }}
{% else %}
    No user have been found.
{% endfor %}

Inherit Templates

{% extends "layout.html" %}

{% block content %}
    Content of the page...
{% endblock %}

Twig

Smarty

PHP Template Engine - Smarty

Another populate template engine is called Smarty, again Smarty was developed for code and HTML separation and to make your templates easier to read.

Output A Variable

{$name}

Foreach Loop

{foreach $users as $user}
{strip}
   <tr bgcolor="{cycle values="#aaaaaa,#bbbbbb"}">
      <td>{$user.name}</td>
      <td>{$user.phone}</td>
   </tr>
{/strip}
{/foreach}

If Statement

{if $name == 'Fred'}
    Welcome Sir.
{elseif $name == 'Wilma'}
    Welcome Ma'am.
{else}
    Welcome, whatever you are.
{/if}

Smarty

Using A Template Engine

The 3 examples on template engines I gave above are not the only template engines available there are loads, and not just for PHP lots of other languages can use a template engine. Even though they are different engines they are all similar in a way, they were all developed to make front-end templating quicker and easier to read. They all mention that this forces separation of your code and makes HTML easier to read because you don't have any PHP tags in your HTML.

But when I've been working with these different engines and I've never enjoyed developing with them. I actually find that they drastically slow down my development because I now have to look up the Smarty syntax or the Twig syntax for the thing I want to do.

What they mention about code separation is exactly right you shouldn't have logic in your HTML, but you don't need a templating system to do this. In a previously tutorial I demonstrated how you can separate your HTML from your code with a simple method using output buffering.

Separate HTML From Code

So dealing with business logic separation is up to the developer to do properly, the benefit of a template language is that it enforces it. But if you were that worried about separation can you use an MVC framework or just create a method and use the ob_buffer to get a HTML contents. If a developer is going to add login to a HTML file they can't complain about separation and not being able to debug easily.

What's mentioned about the template engines being easier to read I also don't agree with, take a foreach in blade for example how different are these pieces of code.

<!-- PHP foreach -->
<?php
foreach ($users as $user)
{
    ?>
    <div class="user"><?php echo $user->name; ?></div>
    <?php
}
?>
<!-- Blade foreach -->
@foreach ($users as $user)
 <div class="user">{{ $user->name }}</div>
@endforeach

There's not much difference between this code, the only difference is your using {{ }} instead of . I even made the PHP do more than I have to. I could of simply used the printf() function to output the div so it will look like this.

<!-- PHP foreach -->
<?php
foreach ($users as $user)
{
    printf('<div class="user">%s</div>', $user->name);
}
?>

Is this really that difficult to read that we have to learn a whole new template language to output variables in your HTML? I don't think so.

Benefit Of Using A Template Engine

From my experience there wasn't a benefit to using a template engine over native PHP templating, but there must be a benefit or there will be no reason to use it.

So I asked this question on Google+, what is the benefit or using a template engine?, one of the answers I had directed me at this post on stackoverflow explaining some of the benefits of using a template engine.

Some of the benefits mentioned are:

  • New syntax
  • Automatic Escaping
  • Template Inheritance
  • Easier for non-developers to read

Now I would argue that learning a new syntax is not a benefit, having to look up the correct syntax every time I need to do a foreach loop, or an if statement is going to take up so much more time that simply using PHP.

Automatic escaping now that is a real benefit, so many developers forget to escape when outputting content on the page, this takes care of that for you. But, it's really not that difficult to create a function that will escape the content of a variable, if you want some good examples there's a formatting file (/wp-includes/formatting.php) in WordPress with loads of escaping functions you can use in different situations. Then you make sure you escape your content before you sending it to the view.

Template inheritance is another good benefit for some pages and could be used for skinning different areas of the site.

Easier for non-developers to read, this is the one I disagree with most. PHP is not a hard language to read, it's not even a hard language to learn. If you have a front-end developer that is changing you HTML and can't understand what your doing with the PHP then I would recommend that they go and learn the basics of PHP. I'm not saying they need to learn how everything works or OOP principles just the basics so they can identify what an if statement is, what a for loop is etc. The native PHP syntax is not that different to the template engine syntax, if they can learn that then they most certainly can learn PHP syntax.

For me the only real benefit to using a template engine is security and autoescaping the output of the HTML.

I'm not here to discourage people from using template engines I can see they have their place but like anything you have to use them on the right projects. It depends on your team for the project, the size of the application, who's coding the HTML, will the content author want to change the HTML, template engines might be perfect for your project.

Here is a good article for reason's why you should be using template engines, Template Engines In PHP.

To conclude, I'm not really a fan of these template engines for me they just add another layer, another language you need to learn with little benefit. So am I going to use this in my future projects? I'm still undecided, I can see they have a place and a reason for being used, but I think things take longer when developing with them and they're not easy to debug with.

Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days