Twig for PHP: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Twig for PHP: Complete Guide to the Symfony Template Engine

\n\n

Twig is a modern, fast, and secure template engine for the PHP language, developed by the Symfony team. It provides developers with a powerful yet intuitive syntax for separating presentation logic (templates) from application business logic. Twig solves a key problem in web development: mixing PHP code with HTML, which leads to "spaghetti code" and reduces project readability and maintainability.

\n\n

The main goal of Twig is to make templates clean, secure, and easy to read. Unlike raw PHP, Twig restricts developers from executing arbitrary code inside templates, which prevents common vulnerabilities such as XSS attacks (Cross-Site Scripting) through automatic output escaping. Instead of complex constructs like <?php foreach(...): ?>, you use concise {% for item in items %}, and instead of <?= $var ?>, you use {{ var }}. This makes templates accessible to layout designers and frontend developers unfamiliar with PHP.

\n\n

Twig is the de facto standard for the Symfony framework, but it also integrates well with Laravel (via the twigbridge package), Drupal, WordPress, and can be used as a standalone library in any PHP project. Thanks to features such as template inheritance, macros, sandboxing, and automatic escaping, Twig is one of the most popular template engines in the PHP ecosystem.

\n\n

Installation

\n

Twig installation is done via the Composer dependency manager. Make sure Composer is installed globally.

\n
composer require twig/twig:^3.0
\n

After executing the command, a vendor/ folder and a composer.json file with the added dependency will appear in your project. Use the standard vendor/autoload.php file for class autoloading.

\n\n

Quick Start: Minimal Working Example

\n

Let's create a simple template and display it. Project structure:

\n
project/\n├── templates/\n│   └── hello.html.twig\n├── vendor/\n└── index.php
\n\n

Template: templates/hello.html.twig

\n
<!DOCTYPE html>\n<html>\n<head>\n    <title>Greeting</title>\n</head>\n<body>\n    <h1>Hello, {{ name }}!</h1>\n    <p>Today is {{ "now"|date("d.m.Y") }}.</p>\n</body>\n</html>
\n\n

PHP script: index.php

\n
<?php\nrequire_once 'vendor/autoload.php';\n\nuse Twig\\Environment;\nuse Twig\\Loader\\FilesystemLoader;\n\n// 1. Create a loader that points to the templates folder\n$loader = new FilesystemLoader('templates');\n\n// 2. Create the Twig environment\n$twig = new Environment($loader, [\n    'cache' => 'cache', // Path for caching (recommended)\n    'auto_reload' => true, // Automatically reload on changes (for development)\n]);\n\n// 3. Render the template, passing variables\necho $twig->render('hello.html.twig', ['name' => 'World']);\n?>
\n

Open index.php in your browser. You will see a page with the title "Hello, World!" and the current date.

\n\n

Main Twig Methods and Functions

\n

Below are the key methods and constructs that form the basis of working with Twig.

\n\n

1. Environment::render() — Template Rendering

\n

Signature: public function render(string $name, array $context = []): string

\n

Description: The main method for displaying a template. It takes the template file name (relative to the loader root) and an associative array of variables (context) that will be available inside the template.

\n
<?php\n//                    

Recommendations