What is twig and how to use it in PHP?
Twig is a modern template engine for PHP, commonly used with frameworks like Symfony, Drupal, or Craft CMS. It helps you separate logic from presentation by allowing you to write cleaner, more readable HTML templates.
Twig is:
- Fast (compiled to native PHP code)
- Secure (auto-escapes variables to prevent XSS)
- Extensible (you can define your own functions, filters, and extensions)
- Widely used (by Symfony, Drupal, Craft CMS, etc.)
Why Use Twig Instead of Plain PHP in Templates?
- Cleaner syntax for HTML templates
- Easier to read and maintain
- Promotes MVC architecture
- Automatic output escaping for security
Features:
{{ }}
for outputting variables{% %}
for control structures like if/for- Template inheritance (
{% extends "base.html.twig" %}
) - Filters (
{{ name|upper }}
→ converts to uppercase)
How to Install and Use Twig in PHP:
1: Install Twig via Composer:
composer require twig/twig
2: Template File: templates/hello.html.twig
<!DOCTYPE html>
<html>
<head>
<title>Hello Twig</title>
</head>
<body>
<h1>Hello {{ name }}!</h1>
</body>
</html>
3: PHP File: index.php
<?php
require_once 'vendor/autoload.php';
// Set up Twig environment
$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader);
// Render template
echo $twig->render('hello.html.twig', ['name' => 'Sandeep']);