DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Introduction To Template-Based Email Design With Spring Boot
  • XSS Prevention Cheatsheet
  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • Create a Login System Using PHP, MySQL, and HTML

Trending

  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • System Coexistence: Bridging Legacy and Modern Architecture
  • After 9 Years, Microsoft Fulfills This Windows Feature Request
  • Introduction to Retrieval Augmented Generation (RAG)
  1. DZone
  2. Coding
  3. Languages
  4. The Ups and Downs of PHP Template Engines

The Ups and Downs of PHP Template Engines

By 
Paul Underwood user avatar
Paul Underwood
·
Sep. 24, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
17.2K Views

Join the DZone community and get the full member experience.

Join For Free

A PHP template engine is a way of outputting PHP in your HTML without using PHP syntax or PHP tags. It's supposed to be used by having a PHP class that will send your HTML the variables you want to display, and the HTML simply displays this data. This means that you are forced to separate your PHP logic from 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 display of code. Another reason why you might use a template engine is because now you have an HTML view file, which you can give to your front-end developer to style, and 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 that I've used are Laravel, Drupal 8 and 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 three examples of template engines I gave above are not the only template engines available. There are many, 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 work with these different engines, I never enjoy 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. However, you don't need a templating system to do this. In a previous tutorial I demonstrated how you can separate your HTML from your code with a simple method using output buffering.

Separate HTML From Code

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

I also don't agree with what's mentioned about the template engines being easier to read. Take a foreach in blade for an example of the difference:

<!-- 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 these code samples, except in Blade you use:

{{ $user->name }}
In PHP, on the other hand, you use:

<?php echo $user->name; ?>
I even made the PHP do more than I have to. I could have simply used the printf() function to output the div, so it would look like this:

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

Is it really so 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

In my experience, there isn't a benefit to using a template engine over native PHP templating, but there must be some benefit, or there would 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 to 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
  • Ease of reading for non-developers

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 than simply using PHP.

Automatic escaping is a real benefit. So many developers forget to escape when outputting content on the page, and 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 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.

The ease of reading for non-developers 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 your HTML and can't understand what you're 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 and OOP principles, but just the basics so they can identify what an if statement is, what a for loop is, and so on. The native PHP syntax is not that different from the template engine syntax, so 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 and whether the content author will want to change the HTML. In some cases, template engines might be perfect for your project.

Here is a good article for reasons why you should be using template engines: Template Engines In PHP.

In conclusion, 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 these 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.



PHP Template Engine HTML

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Introduction To Template-Based Email Design With Spring Boot
  • XSS Prevention Cheatsheet
  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • Create a Login System Using PHP, MySQL, and HTML

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!