Twig Documentation
repository·3.x·Indexed 27 days ago
https://github.com/twigphp/twigDocumentation for the Twig template engine, including advanced customization for creating custom filters, functions, tests, and tags. It covers the Twig Extra Bundle and its extensions: cache-extra for template fragment caching, cssinliner-extra for inlining styles, html-extra for data URIs and class management, intl-extra for locale-aware internationalization, markdown-extra for Markdown/HTML conversion, and string-extra for Unicode manipulation and inflection via the Symfony String component.
What's inside Twig
- The Twig Intl Extension provides a suite of filters for locale-aware internationalization in Twig templates. These filters allow you to format numbers, currencies, dates, times, and lists, as well as retrieve names for countries, currencies, languages, locales, and timezones.
Overview of Twig Markdown Extension
3.xThe Twig Markdown Extension provides two primary filters for converting content between Markdown and HTML formats within Twig templates:Overview of Twig template language
3.xTwig is a flexible, fast, and secure template language for PHP. Its syntax is inspired by the Django and Jinja template languages.Install the String Extension
3.xThe String Extension provides integration with the Symfony String component within Twig. It adds several filters to your templates for Unicode manipulation, slugging, and inflection.Use the Twig HTML Extension
3.xThe Twig HTML Extension provides utilities for handling data URIs, conditionally joining CSS class names, and managing class variants using CVA (Class Variance Authority) patterns within Twig templates.Use the Cache Extension to cache template fragments
3.xThecache-extrapackage provides a Twig extension that integrates with the Symfony Cache component. It introduces acachetag that allows you to wrap specific template fragments to cache their rendered output, improving performance by avoiding re-rendering expensive parts of a template.Install the Twig cache extension
3.xThe
cachetag is part of theCacheExtension, which is not installed by default. You must install it using Composer.Standard Twig projects: Install the specific cache extra package:
composer require twig/cache-extraSymfony projects: Install the
twig/extra-bundleto enable it automatically:composer require twig/extra-bundlecomposer require twig/cache-extraControl whitespace in Twig templates
3.xTwig automatically removes the first newline after a template tag. To manage whitespace more granularly, use whitespace control modifiers on your tags.
Modifiers
- Whitespace trimming (
-): Removes all whitespace (including newlines) on the side the modifier is applied. - Line whitespace trimming (
~): Removes all whitespace except newlines on the side the modifier is applied. Using this on the right side of a tag disables the default removal of the first newline.
Modifiers can be applied to the start (
{%-) or end (-%}) of a tag, or both ({%- ... -%}).Removing whitespace between tags
To remove whitespace between two tags, use an empty comment with the whitespace trimming modifier on both sides.
{#- No leading/trailing whitespace -#} {%- if true -%} {{- value -}} {%- endif -%} {# outputs 'no spaces' #} {# Example: trimming only the left side of a variable tag #} <li{{\{{- value }} </li> {# outputs '<li no spaces </li>' #} {# Example: trimming only the right side of a variable tag #} <li {{~ value }} </li> {# outputs '<li no spaces </li>' #} {# Removing whitespace between two tags using empty comments #} <div> {#--#} <strong>foo</strong> {#--#} </div> {# outputs '<div><strong>foo</strong></div>' #}- Whitespace trimming (
Best practices for cache key naming
3.xTo avoid using a fixed
ttl(), use a "validation" strategy by embedding dynamic information into your cache key. This allows the cache to automatically invalidate when data changes.Rules for keys:
- Do not use reserved characters:
{}()/\@: - Namespace your keys like your templates.
- Embed a version integer that you increment when template code changes.
- Embed unique identifiers (like IDs or timestamps) that change when the underlying data changes.
Example pattern:
{% cache "template_name;version;id;timestamp" %}{% cache "blog_post;v1;" ~ post.id ~ ";" ~ post.updated_at %} {{ post.content }} {% endcache %}- Do not use reserved characters:
Use ChainLoader to mix multiple template sources
3.xIf you need to load templates from different locations (e.g., some from a database and some from the filesystem or an array), use
\Twig\Loader\ChainLoader. This allows you to use logical template names regardless of the underlying storage mechanism.$loader1 = new DatabaseTwigLoader($dbh); $loader2 = new \Twig\Loader\ArrayLoader([ 'base.html.twig' => '{% block content %}{% endblock %}', ]); $loader = new \Twig\Loader\ChainLoader([$loader1, $loader2]); $twig = new \Twig\Environment($loader); echo $twig->render('index.html.twig', ['name' => 'Fabien']);Initialize a Twig Environment
3.xTo use Twig, you must create a central
\Twig\Environmentobject. This object stores configuration, extensions, and handles template loading. Most applications create a single environment instance during initialization. You must provide a loader (e.g.,FilesystemLoader) as the first argument.require_once '/path/to/vendor/autoload.php'; $loader = new \Twig\Loader\FilesystemLoader('/path/to/templates'); $twig = new \Twig\Environment($loader, [ 'cache' => '/path/to/compilation_cache', ]);Install the IntlExtension for country_names
3.xThe
country_namesfunction is part of theIntlExtension, which is not installed by default.For standard Twig projects, install the extension via composer:
composer require twig/intl-extraFor Symfony projects, you must also install the
twig/extra-bundle:composer require twig/extra-bundleIf you are not using Symfony, you must manually add the extension to your Twig environment:
use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension());