Description #
Twig is a modern, flexible, and secure templating language for PHP, designed to separate application logic from presentation in web development.
History #
Twig was created in 2009 by Armin Ronacher, also known for Flask and Jinja2. Inspired by Django and Jinja, Twig was built for Symfony and later became the de facto templating engine for many PHP frameworks. It’s maintained by the Symfony project.
Hello World Code #
<h1>{{ 'Hello, World!' }}</h1>
How to Run #
Option 1: Online
Use an online Twig sandbox: https://twigfiddle.com/
Option 2: Local
Install via Composer:
composer require "twig/twig:^3.0"
Example PHP:
$loader = new \Twig\Loader\ArrayLoader([
'index' => '<h1>{{ message }}</h1>',
]);
$twig = new \Twig\Environment($loader);
echo $twig->render('index', ['message' => 'Hello, World!']);
Key Concepts #
{{ }}
for variable output{% %}
for control structures (if, for, etc.)- Safe by default (auto-escaping enabled)
- Macros and blocks for reusable components
- Template inheritance using
{% extends %}
and{% block %}
- Filter-based value manipulation (e.g.
|upper
) - Highly extensible with custom functions and filters
- Caches templates as PHP for speed
- Popular in Symfony, Drupal, and Bolt
- Inspired by Jinja2 and Django templates
Try It Online #
Fun Facts #
- Twig is to PHP what Jinja is to Python—both are Armin Ronacher’s creations.
- Many developers prefer Twig for its strictness and XSS protection.
- Symfony integrates Twig as the default view layer, promoting clean architecture.
Resources #
Official site
Docs or tutorial
GitHub or interpreter
Community or learning resources