Twig Documentation

repository·3.x·Indexed 27 days ago

https://github.com/twigphp/twig

Documentation 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.

Tokens
61.1K
Snippets
246
Records
385
Agent score
93%

What's inside Twig

  1. Overview of Twig Intl Extension filters

    3.x
    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.
  2. Use the Cache Extension to cache template fragments

    3.x
    The cache-extra package provides a Twig extension that integrates with the Symfony Cache component. It introduces a cache tag that allows you to wrap specific template fragments to cache their rendered output, improving performance by avoiding re-rendering expensive parts of a template.
  3. Install the Twig cache extension

    3.x

    The cache tag is part of the CacheExtension, 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-extra

    Symfony projects: Install the twig/extra-bundle to enable it automatically:

    composer require twig/extra-bundle
    composer require twig/cache-extra
  4. Control whitespace in Twig templates

    3.x

    Twig 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>' #}
  5. Best practices for cache key naming

    3.x

    To 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 %}
  6. Use ChainLoader to mix multiple template sources

    3.x

    If 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']);
  7. Initialize a Twig Environment

    3.x

    To use Twig, you must create a central \Twig\Environment object. 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',
    ]);
  8. Install the IntlExtension for country_names

    3.x

    The country_names function is part of the IntlExtension, which is not installed by default.

    For standard Twig projects, install the extension via composer:

    composer require twig/intl-extra

    For Symfony projects, you must also install the twig/extra-bundle:

    composer require twig/extra-bundle

    If 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());