How to use HTML templates in PHP to separate logic from presentation

Updated: January 12, 2024 By: Guest Contributor Post a comment

Introduction

As web applications grow in complexity, maintaining a clear separation between the application logic and the presentation becomes crucial. This separation, commonly referred to as the Model-View-Controller (MVC) pattern, not only improves the readability and maintainability of the code but also enables designers and developers to work more efficiently by allowing them to focus on their respective areas without stepping on each other’s toes.

In this tutorial, we will explore how to use HTML templates in PHP to achieve this separation. By the end of this tutorial, you will have a solid understanding of how to structure your PHP applications to keep your HTML code separate from your PHP logic.

Understanding the Basics

Before diving into HTML templates, it’s essential to understand why mixing PHP and HTML is generally frowned upon. When PHP code is interlaced with HTML, it becomes cumbersome to read, difficult to debug, and almost impossible for a designer unfamiliar with PHP to make changes to the layout or styling of a web page.

Using templates provides a clean solution to this problem. Templates are essentially pre-formatted HTML files that contain placeholders for dynamic content. These placeholders, sometimes referred to as template variables, will be replaced with actual PHP variables at runtime to render the final output to the user’s browser.

Options for Templating in PHP

PHP developers have several options when it comes to templating:

  • Plain PHP Templates: Using PHP itself as the templating engine, where PHP’s simplicity and flexibility can be harnessed to embed logic directly within HTML through easy-to-understand syntax.
  • Third-party Templating Engines: Engines such as Smarty, Twig, and Blade (Laravel’s templating engine) are mature solutions that come with their own syntax and features designed to streamline the templating process.

Getting Started with Plain PHP Templates

Let’s start with the simplest form of templating, which involves using PHP files as templates. Here, we will create a basic HTML template that displays a list of articles, with article data supplied by PHP.

Step 1: Create the HTML Template

First, we’ll create an HTML file, ‘articles-template.php’, which will act as our template:

<!DOCTYPE html>
<html>
<head>
    <title>Articles</title>
</head>
<body>
    <h1>Latest Articles</h1>
    <ul>
        <?php foreach ($articles as $article): ?>
        <li>
            <h2><?php echo htmlspecialchars($article['title']); ?></h2>
            <p><?php echo htmlspecialchars($article['content']); ?></p>
        </li>
        <?php endforeach; ?>
    </ul>
</body>
</html>

In this simple template, we’re using PHP only to loop through an array of articles and print their details into the list. Notice how the PHP code is minimal and strictly used for displaying the data.

Step 2: Separating the Logic

Next, we create a PHP file, ‘index.php’, where we handle the logic:

In ‘index.php’, we prepare the `$articles` array containing our article data and then include the template file like this:

<?php
$articles = [
    [
        'title' => 'PHP & Templates',
        'content' => 'How to cleanly separate logic from presentation.'
    ],
    // more articles...
];

// Include the template file
include 'articles-template.php';

This way, the `index.php` script handles all the logic behind gathering the data and the template file takes care of rendering it. The `$articles` variable is automatically made available in the scope of the included template file.

Step 3: Rendering the Output

When a user visits ‘index.php’, the server processes the PHP, which then includes the ‘articles-template.php’ file. The articles data will be looped through, and the output will be generated and sent to the user. This output is free from PHP logic – it’s plain HTML except for the dynamic content that’s been injected.

Advantages and Caveats

There are several advantages to using plain PHP templates:

  • Easy to Learn: Since it uses PHP’s native syntax, there’s little to no learning curve involved.
  • No Overhead: Additional libraries or engines entail overhead. With plain PHP templates, you use the built-in functionality of the language, avoiding extra complexity or performance hits.
  • Availability: PHP is installed on nearly every server, making deployment hassle-free without worrying about compatibility with templating engines.

However, there are also caveats:

  • Discipline: It requires discipline not to intermix too much logic in the template files, as there are no technical constraints preventing you from doing so.
  • Limited Templating Features: While PHP is a powerful language, it lacks some specialized templating features present in engines like Twig, such as sandboxing, template inheritance, and filters.

Conclusion

Using HTML templates in PHP can significantly improve the maintainability of your application by keeping the logic separate from the presentation. Although PHP can be used as its own templating engine with minimal overhead and an easy learning curve, for more complex scenarios, you may find the use of dedicated templating engines beneficial.

Remember, the goal of templating is not just cleaner code but also a more robust and efficient development process where developers and designers can collaborate seamlessly. Explore the options, find the right fit for your project, and happy coding!