Master Twig: A Complete Guide to PHP’s Powerful Template Engine
This tutorial explains Twig’s key features, installation via Composer, basic usage with environment and rendering, template inheritance, blocks, caching, loops, conditionals, filters, and debugging, providing clear code examples for PHP developers.
Key Points
Twig is a popular PHP template engine developed by Sensio Labs that reduces PHP verbosity and adds security and debugging features.
It can run on both the front‑end and back‑end of a project, serving designers and developers alike.
Twig uses a central Environment object to store configuration, extensions, and to load templates from the filesystem or other sources.
It supports template inheritance (blocks) to avoid duplication and can cache compiled templates for faster subsequent requests.
Conditional statements, loops, and filters control how data is displayed, and a built‑in dump() function aids debugging.
Installation
Install Twig via the official tarball or, more commonly, with Composer: composer require twig/twig Assume PHP and Composer are already installed globally.
Basic Usage
Create a bootstrap.php file to set up Twig:
<?php
require_once __DIR__.'/vendor/autoload.php';
$loader = new Twig_Loader_Filesystem(__DIR__.'/templates');
$twig = new Twig_Environment($loader);
?>In index.php, load data and render a template:
<?php
require_once __DIR__.'/bootstrap.php';
$products = [
['name'=>'Notebook','description'=>'Core i7','value'=>800.00,'date_register'=>'2017-06-22'],
['name'=>'Mouse','description'=>'Razer','value'=>125.00,'date_register'=>'2017-10-25'],
['name'=>'Keyboard','description'=>'Mechanical Keyboard','value'=>250.00,'date_register'=>'2017-06-23'],
];
echo $twig->render('index.html', ['products'=>$products]);
?>Template Inheritance (Layout)
Create layout.html with a block placeholder:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Tutorial Example</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>Then extend it in index.html:
{% extends "layout.html" %}
{% block content %}
<table border="1" style="width:80%;">
<thead>
<tr><td>Product</td><td>Description</td><td>Value</td><td>Date</td></tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{{ product.name }}</td>
<td>{{ product.description }}</td>
<td>{{ product.value }}</td>
<td>{{ product.date_register|date("m/d/Y") }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}Caching
Enable compiled‑template caching by passing a cache directory to the environment:
$twig = new Twig_Environment($loader, ['cache' => '/templates/cache']);This caches the compiled PHP version of templates, not the rendered output.
Loops
Iterate over arrays or ranges:
{% for product in products %}
...
{% endfor %}
{% for number in 0..100 %}
{{ number }}
{% endfor %}
{% for letter in 'a'..'z' %}
{{ letter }}
{% endfor %}Conditional loops can filter items, e.g., only products with a value below 250:
{% for product in products if product.value < 250 %}
...
{% endfor %}Conditionals
Use if, elseif, else tags to control output:
{% for product in products %}
{% if product.value > 500 %}
<tr>...</tr>
{% endif %}
{% endfor %}Filters
Common filters include date, date_modify, format, striptags, and escape (HTML, JS, CSS, URI contexts). Example:
{{ product.date_register|date("m/d/Y") }}
{{ product.date_register|date_modify("+1 day")|date("m/d/Y") }}
{{ "This product description is: %s"|format(product.description) }}
{{ product.description|escape }}Debugging
Enable the debug extension and use dump() to inspect variables:
$twig = new Twig_Environment($loader, ['debug'=>true]);
$twig->addExtension(new Twig_Extension_Debug());
{{ dump(products) }}Conclusion
The article aims to help developers master Twig’s fundamentals and start using it in projects immediately.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
