Skip to Content
Course content

39: Templating Engines in PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why can't I just keep mixing PHP and HTML in the same file?

Look, when you're building a tiny project, mixing echo statements with HTML tags feels fast. But I've spent way too many hours in my career cleaning up "spaghetti code" where a single .php file contains database queries, business logic, and a mess of nested <div> tags. It's a nightmare to maintain.

A templating engine enforces a strict separation of concerns. Your PHP code handles the "how" (fetching data, calculating totals), and the template handles the "where" (the layout). If a designer needs to change a CSS class, they shouldn't have to worry about accidentally deleting a semicolon and crashing the entire server with a Parse Error. By using an engine, you're basically creating a safe sandbox for your presentation layer.

Is Twig actually better than just using plain PHP?

In the PHP world, Twig is the industry standard for a reason. While you can technically do anything in plain PHP, Twig makes the common stuff cleaner and—more importantly—safer. One of the biggest wins is automatic output escaping. In plain PHP, if you forget htmlspecialchars() when printing user-generated content, you've just opened yourself up to an XSS attack. Twig handles that by default.

Compare the syntax for a simple product list. In plain PHP, it's a bit clunky:

<ul>
    <?php foreach ($products as $product): ?>
        <li><?php echo htmlspecialchars($product['name']); ?> - $<?php echo number_format($product['price'], 2); ?></li>
    <?php endforeach; ?>
</ul>

Now, here is the same thing in Twig. It's much more readable and feels like it belongs in an HTML file:

<ul>
    {% for product in products %}
        <li>{{ product.name }} - ${{ product.price|number_format(2) }}</li>
    {% endfor %}
</ul>

How do I actually integrate an engine into my app?

You don't write these engines from scratch; you install them via Composer. Once you've run composer require "twig/twig:^3.0", you need to set up the environment. You tell Twig where your templates are stored and where it should save the compiled PHP versions of those templates (since Twig compiles down to plain PHP for speed).

Here is a real-world setup for a page that displays a user's dashboard:

require_once 'vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader, [
    'cache' => 'cache/twig', // I always recommend enabling this in production
]);

// Your business logic stays here in the PHP file
$user = ['name' => 'Alex', 'role' => 'Administrator'];
$notifications = ['Password changed', 'New login from New York', 'Payment successful'];

echo $twig->render('dashboard.twig', [
    'user' => $user,
    'alerts' => $notifications
]);

Does using a templating engine slow down my site?

Technically, yes, there is a tiny bit of overhead because the engine has to parse the template. But here is the secret: Twig compiles your templates into raw PHP code and caches them. After the first time a page is loaded, Twig isn't "interpreting" the template anymore; it's just executing the cached PHP file.

In my experience, the performance hit is negligible—we're talking milliseconds—while the gain in developer productivity and security is massive. If you're at a scale where a templating engine is your primary bottleneck, you probably have much bigger architectural problems to solve first.




📋 Practical Task

Build a Dynamic Product Inventory Gallery with Twig

You are tasked with creating a product gallery page. Instead of using plain PHP, you will implement this using the Twig templating engine.

  • The Setup: Use Composer to install Twig in a fresh directory.
  • The Data: Create a PHP script that defines an array of at least five products. Each product should be an associative array containing a name, price, category, and in_stock (boolean).
  • The Template: Create a gallery.twig file.
    • Use a {% for %} loop to iterate through the products.
    • Use an {% if %} statement to display a "Sold Out" badge if in_stock is false, otherwise display the price.
    • Apply a filter to ensure the product name is capitalized.
  • The Execution: Configure the Twig environment in your PHP script to render the gallery.twig template and pass the product array to it.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.