In this blog post, we will dive into using Twig, a powerful and flexible templating engine for PHP, to build hierarchical templates and render pages. We will cover installation, basic syntax, template inheritance, and other features to help you harness the power of Twig in your PHP projects.

1. Introduction to Twig

Twig is a modern templating engine for PHP designed to provide a fast, secure, and efficient way of handling templates. It offers a concise and clean syntax that is easy to learn and maintain. Some of the key features of Twig include:

  • Template inheritance
  • Automatic escaping for secure templates
  • Extensibility through custom functions, filters, and tags
  • High performance with compiled templates

2. Installing Twig

To get started with Twig, you’ll need to install it using Composer. Run the following command in your terminal:

composer require "twig/twig:^3.0"

3. Twig Basics

Create a templates directory in your project to store your Twig templates. These templates use the .twig file extension. Twig templates use a simple syntax for variables, control structures, and functions:

  • {{ variable }}: output a variable
  • {% if condition %}...{% endif %}: conditional statements
  • {% for item in items %}...{% endfor %}: loops
  • {{ function() }}: function calls

4. Template Inheritance

One of Twig’s most powerful features is template inheritance. This allows you to build a base template with common elements, such as headers and footers, and extend it in child templates.

Create a base.twig file in your templates directory:

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
    <header>
        {% block header %}{% endblock %}
    </header>

    <main>
        {% block content %}{% endblock %}
    </main>

    <footer>
        {% block footer %}{% endblock %}
    </footer>
</body>
</html>

5. Using Blocks for Hierarchical Templates

In the base.twig file, we use {% block block_name %} to define blocks that can be overridden by child templates. Let’s create a child template called page.twig:

{% extends "base.twig" %}

{% block title %}Page Title{% endblock %}

{% block header %}
    <h1>Welcome to My Website</h1>
{% endblock %}

{% block content %}
    <p>This is the main content of the page.</p>
{% endblock %}

{% block footer %}
    <p>Footer text goes here.</p>
{% endblock %}

The child template page.twig extends base.twig and overrides the blocks defined in the base template.

6. Rendering Pages with Twig

To render a Twig template in your PHP script, you’ll need to follow these steps:

  1. Create an instance of the TwigEnvironment class.
  2. Configure it with the path to your templates directory.
  3. Use the render() method to render the template with any data you want to pass to it.

Here’s an example:

<?php
require_once 'vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader);

$data = [
    'pageTitle' => 'My Custom Page Title',
    'content' => 'This is the custom content of the page.',
];

echo $twig->render('page.twig', $data);

In this example, we pass an array of data to the render() method, which contains the pageTitle and content variables. The page.twig template can access these variables using the {{ variable }} syntax. If you want to use the variables in the parent base.twig template, make sure to override the appropriate blocks in the child template and pass the variables, like so:

{% extends "base.twig" %}

{% block title %}{{ pageTitle }}{% endblock %}

{% block header %}
    <h1>Welcome to My Website</h1>
{% endblock %}

{% block content %}
    <p>{{ content }}</p>
{% endblock %}

{% block footer %}
    <p>Footer text goes here.</p>
{% endblock %}

Now you’ve learned how to use Twig in PHP to build hierarchical templates and render pages based on them. By leveraging the power of template inheritance and blocks, you can create clean, maintainable, and flexible templates for your PHP projects.