Twig is a modern, fast, secure, and flexible templating engine for PHP. Developed by Fabien Potencier (the creator of Symfony), Twig allows developers to separate the presentation layer (HTML, CSS, JavaScript) from the application logic (PHP code). This separation enhances maintainability, readability, and collaboration in web development projects.
Key features and benefits of Twig include:
* Concise and Readable Syntax: Twig's syntax is designed to be developer-friendly, making templates easy to write and understand. It uses specific delimiters for different types of operations:
* `{{ ... }}`: For printing the content of a variable or the result of an expression.
* `{% ... %}`: For executing statements like loops, conditionals, or setting variables.
* `{# ... #}`: For comments.
* Separation of Concerns: Enforces a clear division between business logic and presentation, leading to cleaner codebases and easier template management. Designers can work on templates without needing to understand complex PHP logic.
* Security (Automatic Escaping): By default, Twig automatically escapes variables, preventing XSS (Cross-Site Scripting) vulnerabilities. This significantly reduces the risk of security issues caused by injecting malicious code into the output.
* Performance: Twig compiles templates into plain optimized PHP classes. This compilation happens only once (or when templates change), and the compiled templates are then cached, leading to minimal overhead and excellent performance comparable to native PHP templates.
* Extensibility: Twig is highly extensible. Developers can define custom tags, filters, functions, and global variables to tailor the templating engine to their specific needs.
* Template Inheritance: A powerful feature that allows templates to share common layouts. You can define a base template with blocks and then extend it in child templates to override or add content to those blocks, promoting code reuse and consistency.
* Debugging Tools: Twig includes useful debugging features to help identify issues within templates.
In essence, Twig acts as a middle layer between your PHP application and the final HTML output. Your PHP code prepares data, passes it to Twig, and Twig then renders this data into your predefined templates, producing the HTML that is sent to the user's browser. It's a fundamental component in many modern PHP frameworks like Symfony and Laravel (via optional packages).
To use Twig, you typically install it via Composer:
`composer require twig/twig`
Example Code
<?php
require_once __DIR__ . '/vendor/autoload.php';
// To make this example runnable:
// 1. Create a directory named 'templates' in the same directory as this PHP file.
// 2. Inside 'templates', create a file named 'index.twig' with the content provided below.
// 3. Run 'composer require twig/twig' in your project root to generate 'vendor/autoload.php'.
// 1. Define your template directory where Twig will look for templates
$loader = new \Twig\Loader\FilesystemLoader(__DIR__ . '/templates');
// 2. Initialize Twig environment
// The second argument is an array of options. 'cache' is crucial for performance in production.
// For this example, 'cache' is disabled and 'debug' is enabled for easier development and error visibility.
$twig = new \Twig\Environment($loader, [
'cache' => false, // Set to a real path like __DIR__ . '/cache' in production for performance
'debug' => true,
]);
// 3. Add debug extension (optional, but highly recommended during development for the dump() function)
$twig->addExtension(new \Twig\Extension\DebugExtension());
// 4. Prepare data that will be passed to the template
$products = [
['name' => 'Laptop', 'price' => 1200.00, 'in_stock' => true],
['name' => 'Mouse', 'price' => 25.50, 'in_stock' => true],
['name' => 'Keyboard', 'price' => 75.00, 'in_stock' => false],
['name' => 'Monitor', 'price' => 300.00, 'in_stock' => true],
];
$user = [
'name' => 'John Doe',
'is_admin' => true,
];
// 5. Render the 'index.twig' template with the prepared data
try {
echo $twig->render('index.twig', [
'title' => 'Product List',
'products' => $products,
'user' => $user,
'welcome_message' => 'Welcome to our store!',
]);
} catch (\Twig\Error\LoaderError $e) {
echo "Loader Error: " . $e->getMessage();
} catch (\Twig\Error\RuntimeError $e) {
echo "Runtime Error: " . $e->getMessage();
} catch (\Twig\Error\SyntaxError $e) {
echo "Syntax Error: " . $e->getMessage();
} catch (Exception $e) {
echo "An unexpected error occurred: " . $e->getMessage();
}
?>
<!-- File: templates/index.twig -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title|e }}</title> {# 'e' filter for HTML escaping, though auto-escaping is default and recommended #}
<style>
body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; color: #333; }
h1, h2 { color: #0056b3; margin-bottom: 15px; }
.product-list { list-style: none; padding: 0; border-top: 1px solid #eee; margin-top: 20px; }
.product-item { background-color: #ffffff; border: 1px solid #ddd; border-top: none; margin-bottom: 0; padding: 12px 15px; display: flex; justify-content: space-between; align-items: center; }
.product-item:first-child { border-top: 1px solid #ddd; }
.price { font-weight: bold; color: #28a745; margin-left: 10px; }
.out-of-stock { color: #dc3545; font-style: italic; margin-left: 10px; }
.admin-note { background-color: #e6ffed; padding: 10px 15px; border-left: 4px solid #28a745; margin-top: 20px; margin-bottom: 20px; color: #155724; border-radius: 4px; }
.user-greeting { margin-top: 10px; margin-bottom: 10px; }
</style>
</head>
<body>
<h1>{{ welcome_message|upper }}</h1> {# Using a filter to convert a string to uppercase #}
{% if user.is_admin %}
<p class="admin-note">Hello, {{ user.name }}. You are an administrator. You have special privileges.</p>
{% else %}
<p class="user-greeting">Hello, {{ user.name }}.</p>
{% endif %}
<h2>Available Products</h2>
{# Check if the products array has items before looping #}
{% if products|length > 0 %}
<ul class="product-list">
{# Loop through each product in the 'products' array #}
{% for product in products %}
<li class="product-item">
<span>{{ product.name }}</span>
<div>
<span class="price">${{ product.price|number_format(2, '.', ',') }}</span>
{# Conditional display based on 'in_stock' status #}
{% if not product.in_stock %}
<span class="out-of-stock">(Out of Stock)</span>
{% else %}
<span>(In Stock)</span>
{% endif %}
</div>
</li>
{% endfor %}
</ul>
{% else %}
<p>No products available at the moment. Please check back later!</p>
{% endif %}
{# This is a Twig comment. It will not appear in the final HTML output. #}
{# You can also use the dump() function during debugging: {{ dump(user) }} #}
</body>
</html>








twig/twig