Learn Symfony · 3/12

Views and the Twig Templating Engine

9 min read

In a modern web application, sending data from your database to the user is only half the battle. The other half is making that data look presentable. If your controllers are generating raw HTML strings and echoing them back to the browser, you are likely writing code that is impossible to read, a nightmare to maintain, and vulnerable to security attacks.

Welcome to the presentation layer. In this guide, we will explore Twig, Symfony's default templating engine, and learn how to build dynamic, reusable, and secure user interfaces.


1. Introduction to Twig: Syntax and Basic Output

The Problem

Imagine you are running a restaurant. The kitchen (your Controller) prepares the food (data), but you wouldn't just throw a raw steak at a customer from across the room. You need a waiter to plate it properly, add the garnish, and present it at the table.

Historically, PHP developers mixed HTML and PHP logic in the same file.

php
// The old, messy way
echo "<div class='user-profile'>";
echo "<h1>Welcome, " . htmlspecialchars($user->getName()) . "!</h1>";
if ($user->isAdmin()) { echo "<button>Delete Everything</button>"; }
echo "</div>";

This is error-prone. If you forget htmlspecialchars, a malicious user can inject JavaScript into your page (an XSS attack). If a frontend developer who only knows HTML needs to redesign this page, they will be terrified of breaking the PHP syntax.

The Definition

Twig is a modern, compiled templating engine for PHP. It safely separates your application logic from your presentation logic.

Under the hood: Twig takes your .html.twig files and compiles them down to highly optimized, raw PHP files. It caches these compiled files, meaning Twig is incredibly fast—there is virtually no performance overhead compared to writing raw PHP templates. Furthermore, it automatically escapes all output by default, protecting you from Cross-Site Scripting (XSS) attacks automatically.

Installation / Setup

In a standard Symfony Webapp project, Twig is usually pre-installed. However, if you started from a micro-skeleton, you must install it using Composer:

bash
composer require symfony/twig-bundle

Once installed, Symfony creates a templates/ directory where all your Twig files will live.

The Syntax

Twig has an extremely minimalistic syntax. It only has three core constructs. Think of them as the alphabet of the engine:

  1. {{ ... }} : "Say Something" (Output)
    Used to print the result of a variable or an expression to the template.

    twig
    <h1>Welcome, {{ username }}!</h1>
  2. {% ... %} : "Do Something" (Logic/Control)
    Used for statements like loops, conditionals, and setting variables.

    twig
    {% set username = 'John Doe' %}
  3. {# ... #} : "Hide Something" (Comments)
    Used to add comments. These are stripped out entirely during the compilation process and will never be seen by the end user in the browser's "View Source" tab.

    twig
    {# The user will never see this. I am hiding my bad CSS classes here. #}

Industry Practice: Passing Data from Controller to View

In industry, controllers should be "thin". They fetch data and pass an array of variables directly to the Twig template.

php
// src/Controller/UserController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class UserController extends AbstractController
{
    #[Route('/profile', name: 'user_profile')]
    public function profile(): Response
    {
        $userData = [
            'name' => 'Alice',
            'role' => 'Admin'
        ];

        // The render() method is provided by AbstractController
        return $this->render('user/profile.html.twig', [
            'user' => $userData,
        ]);
    }
}
twig
{# templates/user/profile.html.twig #}
<div class="profile-card">
    <h2>{{ user.name }}</h2>
    <p>Role: {{ user.role }}</p>
</div>

2. Template Inheritance: Building a DRY User Interface

The Problem

Almost every page on a website shares the same header, navigation bar, footer, and <head> metadata (like CSS links). If you copy and paste this standard HTML structure into 50 different files, and then your marketing team asks you to update the copyright year in the footer, you now have to edit 50 different files. If you miss one, you have introduced an inconsistency.

The Definition

Template Inheritance is a feature that allows you to define a base "skeleton" template containing your common HTML structure, and "blocks" which act as placeholders. Child templates can then "extend" this base template and overwrite only the specific blocks they care about.

Imagine standard office forms where the company letterhead, border, and footer are pre-printed. As an employee, you only fill out the blank boxes (the blocks). You do not redraw the company logo every time you write a memo.

How it Works

1. The Base Template (The Skeleton)
Usually located at templates/base.html.twig. We define placeholders using the {% block block_name %} syntax.

twig
{# templates/base.html.twig #}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
    </head>
    <body>
        <nav>
            <ul>
                <li><a href="/">Home</a></li>
                <li><a href="/about">About</a></li>
            </ul>
        </nav>

        <main>
            {# This is the main placeholder for child templates #}
            {% block body %}{% endblock %}
        </main>

        <footer>
            <p>&copy; 2026 My Awesome Company</p>
        </footer>
    </body>
</html>

2. The Child Template (The Content)
When creating a specific page, you declare that it extends the base template, and you only define what goes inside the blocks.

twig
{# templates/home/index.html.twig #}
{% extends 'base.html.twig' %}

{% block title %}Homepage - My Awesome Company{% endblock %}

{% block body %}
    <h1>Welcome to the Homepage</h1>
    <p>This paragraph will be injected directly into the main tag of the base template!</p>
{% endblock %}

Industry Standard

In enterprise applications, you rarely have just one base template. You will often see a hierarchy:

  • base.html.twig (Core layout)
    • admin_base.html.twig (Extends base, adds admin sidebar)
      • admin_dashboard.html.twig (Extends admin_base, contains specific dashboard widgets)

3. Control Structures: Ifs, Loops, and Custom Filters

The Problem

Data from your database is rarely a single, perfectly formatted string. You will receive arrays of hundreds of users, timestamps that look like 1708837500, and boolean flags that dictate whether a user is banned. You need a way to loop through arrays, conditionally render HTML, and format raw data into human-readable text directly in the presentation layer.

The Definition

Control Structures are Twig tags (using {% %}) that handle the logic of your view, such as if statements for conditionals and for loops for iteration. Filters are modifiers (applied using the pipe symbol |) that transform data before it is output.

If Statements and Loops

Twig's for and if loops behave predictably, much like PHP or JavaScript, but with quality-of-life enhancements for presentation.

twig
{# templates/product/list.html.twig #}
<ul>
    {% for product in products %}
        <li>
            {{ product.name }} 
            
            {% if product.stock > 0 %}
                <span class="in-stock">In Stock</span>
            {% else %}
                <span class="out-of-stock">Sold Out</span>
            {% endif %}
        </li>
    {% else %}
        {# INDUSTRY TRICK: The 'else' tag inside a 'for' loop triggers if the array is completely empty! #}
        <li>No products found matching your search.</li>
    {% endfor %}
</ul>

Fun Fact: If you ever tried to write an "empty state" check in standard PHP, you know you usually have to write if(empty($products)) around your foreach loop. Twig's {% else %} inside a {% for %} loop is a massive time saver and keeps the code incredibly clean.

Filters: Formatting Data

Filters transform the data on the left side of the pipe |. You can chain them together.

twig
{# Convert a string to upper case #}
<h2>{{ user.name|upper }}</h2>

{# Format a raw date object or timestamp into a readable string #}
<p>Joined on: {{ user.createdAt|date('F j, Y') }}</p>

{# Default filter: Provide a fallback if a variable is null or undefined #}
<p>Bio: {{ user.bio|default('This user has not written a bio yet.') }}</p>

Industry Standard: Custom Twig Extensions

Sometimes, the built-in Twig filters aren't enough. For example, if your business requires displaying prices in a highly specific format based on regional tax laws, writing that logic in the view is bad practice.

Instead, Symfony allows you to create Twig Extensions. You write the logic in standard PHP, register it, and it becomes available in every Twig file as a custom filter (e.g., {{ product.price|calculate_regional_tax }}). This keeps your templates purely focused on presentation, while PHP handles the heavy business logic.


4. Managing CSS, JS, and Images with the Asset Component

The Problem

When building a website, you need to include images, stylesheets (CSS), and JavaScript.
If you write <img src="/images/logo.png">, it might work on your local machine. But what if your application is deployed to a subdirectory on production (e.g., https://mycompany.com/app/)? Suddenly, your paths break.

Furthermore, when you update style.css and deploy, returning visitors might still see the old design because their browser has cached the old CSS file.

The Definition

The Symfony Asset component is a tool that manages the URL generation for your static web assets. It guarantees that URLs point to the correct directories regardless of how your application is hosted, and it natively supports versioning to automatically break browser caches when you deploy new files.

Installation / Setup

In modern Symfony, ensure the asset component is installed:

bash
composer require symfony/asset

Usage in Twig

Instead of hardcoding the path to your static files, you wrap the path in the asset() Twig function.

twig
{# BAD: Hardcoded path #}
<link rel="stylesheet" href="/css/styles.css">
<img src="/images/logo.png" alt="Company Logo">

{# GOOD: Using the Asset function #}
<link rel="stylesheet" href="{{ asset('css/styles.css') }}">
<img src="{{ asset('images/logo.png') }}" alt="Company Logo">

How it Solves the Problem

  1. Directory Independence: If you move your app to a subdirectory, asset('css/styles.css') automatically figures out the base URL and outputs /app/css/styles.css. No broken links.
  2. Cache Busting (Versioning): Under the hood, you can configure Symfony to append a version hash to your assets (e.g., styles.css?v=1a2b3c). When you deploy an update, the hash changes, forcing the user's browser to download the fresh, new CSS file instead of relying on the stale cached version.

(Note: In Symfony 7+, the modern industry standard is moving towards symfony/asset-mapper, which handles not only paths and versioning but also ES6 JavaScript modules directly without needing NodeJS or Webpack. However, the asset() function remains the foundational concept for referencing any public file.)


References & Further Reading

Challenge

Challenge: Build a User Profile Page with Twig

You are tasked with creating a dynamic user profile page using Twig's templating features. This involves creating a reusable base layout and a specific profile template that extends it.

Assume a controller passes a user object to the user_profile.html.twig template. This object has the following properties:

  • name: (string) e.g., "Jane Doe"
  • profilePictureUrl: (string) e.g., "images/avatars/jane.png"
  • isVerified: (boolean)
  • registeredAt: (DateTime object)
  • recentActivities: (array of objects), where each object has a description property.

File 1: templates/base.html.twig

  1. Create a basic HTML5 skeleton.
  2. Define a Twig block named title inside the <title> tag. Provide a default value of "My Application".
  3. Define a block named stylesheets inside the <head>.
  4. Inside the stylesheets block, add a <link> tag for a stylesheet. Use the asset() function to generate the path for css/main.css.
  5. Define a block named content inside the <body>.

File 2: templates/user_profile.html.twig

  1. This template must extend templates/base.html.twig.
  2. Override the title block to display "User Profile - " followed by the user's name.
  3. Override the content block to render the user's profile information:
    • Display the user's name in all uppercase letters.
    • Display the user's profile picture using an <img> tag. The src attribute must be generated using the asset() function with the user.profilePictureUrl variable.
    • Conditionally display the text <strong>(VERIFIED)</strong> only if the user.isVerified property is true.
    • Display the user's registration date formatted as Month Day, Year (e.g., "October 26, 2023").
    • Use a for loop to iterate over the user.recentActivities array. For each activity, display its description in a list item <li>.
    • If the user.recentActivities array is empty, the loop should instead display a single list item with the text "No recent activity."
    • Include a Twig comment anywhere inside this file that will not be rendered in the final HTML.

Expected result

Your final submission should consist of two Twig files as described.

templates/base.html.twig

This file should define the main layout structure with placeholders for content.

twig
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{% block title %}My Application{% endblock %}</title>
    {% block stylesheets %}
        <link rel="stylesheet" href="{{ asset('css/main.css') }}">
    {% endblock %}
</head>
<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

templates/user_profile.html.twig

This file should extend the base layout and fill the blocks with dynamic user data, using control structures, filters, and the asset function.

twig
{% extends 'base.html.twig' %}

{# This is a comment about the user profile template. #}

{% block title %}User Profile - {{ user.name }}{% endblock %}

{% block content %}
    <h1>{{ user.name|upper }} {% if user.isVerified %}<strong>(VERIFIED)</strong>{% endif %}</h1>
    
    <img src="{{ asset(user.profilePictureUrl) }}" alt="Profile picture for {{ user.name }}">

    <p>Member since: {{ user.registeredAt|date('F j, Y') }}</p>

    <h2>Recent Activity:</h2>
    <ul>
        {% for activity in user.recentActivities %}
            <li>{{ activity.description }}</li>
        {% else %}
            <li>No recent activity.</li>
        {% endfor %}
    </ul>
{% endblock %}
twig

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.