Using Symfony with Twig templates to render dynamic HTML pages

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

Introduction

In this tutorial, we are going to delve into the integration of Symfony and Twig to create dynamic HTML pages. Symfony is a robust PHP framework for web applications, and Twig is its default templating engine. Twig provides a flexible, fast, and secure template language to design beautiful layouts with minimal fuss.

Before we begin, make sure you have installed PHP, Composer (a dependency manager for PHP), and Symfony on your development machine. You should also set up a Symfony project. If you haven’t, you can do so by executing symfony new my_project_name --full in your terminal.

Understanding Symfony and Twig

Symfony’s structure is logical and file-based. Symfony employs controllers to handle client requests and return responses, usually in the form of an HTML page. Controllers can return responses directly, but in most cases, they delegate the rendering of HTML content to templates, which is where Twig comes in.

Twig is a templating engine that uses its own syntax but can integrate seamlessly with PHP to add dynamics to HTML. It allows for variable interpolation, loops, conditionals, and other control structures directly within your templates.

Setting Up Your Controller

Let’s start by setting up a simple controller. In Symfony, controllers are often placed within the src/Controller directory. Here’s an example of a basic controller:

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class PageController {
    /**
     * @Route("/hello/{name}", name="hello_page")
     */
    public function hello($name) : Response {
        return new Response(
            '<html><body>Hello ' . $name . '!</body></html>'
        );
    }
}

This controller will display a simple hello message. However, we want to use Twig to render our templates. Let’s modify the hello method to do so.

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class PageController extends AbstractController {
    ...
    public function hello($name) : Response {
        return $this->render(
            'hello.html.twig',
            ['name' => $name]
        );
    }
}

To use the render method, we extend the AbstractController, which provides several convenient tricks for common tasks, rendering templates being one of them.

Creating Your Twig Template

Now, let’s create the Twig template file. Templates in Symfony are usually stored in the templates directory. A typical convention would be to have a base.html.twig that serves as a layout for other individual template files. Here’s a simple base.html.twig:

<!-- templates/base.html.twig -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Hello{% endblock %}</title>
</head>
<body>
    {% block body %}{% endblock %}
</body>
</html>

And the corresponding hello.html.twig:

<!-- templates/hello.html.twig -->
{% extends 'base.html.twig' %}

{% block title %}Hello {{ name }}!{% endblock %}

{% block body %}
<p>Hello {{ name }}!</p>
{% endblock %}

In hello.html.twig, we extend base.html.twig and override the title and body blocks. We use Twig’s double curly braces {{ }} for outputting the name variable passed from the controller.

More on Twig

Twig has many powerful features for template inheritance, loops, conditionals, filters, and functions. Let’s explore some examples.

Looping

If you have an array of data to display, Twig makes it easy to iterate over items:

{% for user in users %}
    <li>{{ user.name }}</li>
{% endfor %}

Conditionals

Twig also supports conditional statements, much like PHP’s if clause:

{% if users is empty %}
    <p>No users found.</p>
{% else %}
    <ul>
        {% for user in users %}
            <li>{{ user.name }}</li>
        {% endfor %}
    </ul>
{% endif %}

Filters

Filters allow you to manipulate variables. Take uppercase for example:

Hello {{ name|upper }}!

Twig can do much more, like including partials, macros, or extending blocks from other templates. It makes your template manageable, reusable, and neat.

Conclusion

By integrating Symfony with Twig, you will construct dynamic, easy to maintain, and secure web applications with an elegant syntax and robust design patterns.\

Happy coding & have a nice day!