### Install IntlExtension with Composer Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/format_date.rst Install the IntlExtension using Composer to enable date and time formatting filters. ```bash composer require twig/intl-extra ``` -------------------------------- ### Installing the String Extension via Composer Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/plural.rst Shows the composer command to install the StringExtension, which is required for the plural filter. ```bash $ composer require twig/string-extra ``` -------------------------------- ### Install MarkdownExtension via Composer Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/html_to_markdown.rst Install the MarkdownExtension using Composer, which is required for the html_to_markdown filter. ```bash $ composer require twig/markdown-extra ``` -------------------------------- ### Install IntlExtension via Composer Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/currency_symbol.rst Instructions for installing the Twig IntlExtension using Composer, which is required for the currency_symbol filter. ```bash $ composer require twig/intl-extra ``` -------------------------------- ### Install Inky Extension with Composer Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/inky_to_html.rst Install the InkyExtension using Composer. This is required to use the inky_to_html filter. ```bash $ composer require twig/inky-extra ``` -------------------------------- ### Installing HtmlExtension Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/html_attr_type.rst Provides instructions for installing the HtmlExtension, which is required for the html_attr_type filter. Includes Composer commands and explicit extension addition for Twig environments. ```bash $ composer require twig/html-extra ``` ```bash $ composer require twig/extra-bundle ``` ```php use Twig\Extra\Html\HtmlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new HtmlExtension()); ``` -------------------------------- ### Install HtmlExtension via Composer Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/data_uri.rst Install the necessary HtmlExtension for the data_uri filter using Composer. This is a prerequisite for using the filter. ```bash $ composer require twig/html-extra ``` -------------------------------- ### Install CacheExtension via Composer Source: https://github.com/twigphp/twig/blob/3.x/doc/tags/cache.rst Install the CacheExtension using Composer. This extension is required for the cache tag functionality. ```bash $ composer require twig/cache-extra ``` -------------------------------- ### Install Twig Extra Bundle in Symfony Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/currency_symbol.rst Instructions for installing the twig/extra-bundle in Symfony projects, which includes the IntlExtension. ```bash $ composer require twig/extra-bundle ``` -------------------------------- ### Environment Setup and Template Loading Source: https://github.com/twigphp/twig/blob/3.x/doc/api.rst Demonstrates how to create a Twig environment and load a template using the FilesystemLoader. ```APIDOC ## Environment Setup and Template Loading ### Description This section shows the typical way to configure Twig by creating an environment object and setting up a loader to find templates. ### Method Constructor and method calls ### Endpoint N/A (PHP API) ### Parameters #### Environment Constructor - **loader** (*object*) - Required - An instance of a Twig Loader (e.g., \Twig\Loader\FilesystemLoader). - **options** (*array*) - Optional - An array of configuration options for the environment. #### Options Array - **cache** (*string* or *false*) - Optional - An absolute path for compiled templates, or false to disable. ### Request Example ```php 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', ]); $template = $twig->load('index.html.twig'); ``` ### Response #### Success Response - **twig** (*object*) - An instance of \Twig\Environment. - **template** (*object*) - An instance of \Twig\TemplateWrapper. ``` -------------------------------- ### Install Twig with Composer Source: https://github.com/twigphp/twig/blob/3.x/doc/installation.rst Use this command to add Twig to your project dependencies via Composer. Ensure Composer is installed and in your PATH. ```bash composer require "twig/twig:^3.0" ``` -------------------------------- ### Twig Profiler Extension Setup Source: https://github.com/twigphp/twig/blob/3.x/doc/api.rst Initializes and uses the Twig Profiler extension to gather performance metrics for template executions. ```php $profile = new \Twig\Profiler\Profile(); $twig->addExtension(new \Twig\Extension\ProfilerExtension($profile)); $dumper = new \Twig\Profiler\Dumper\TextDumper(); echo $dumper->dump($profile); ``` -------------------------------- ### Basic Usage of format_datetime Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/format_datetime.rst Formats a date-time string using the default settings. Ensure the IntlExtension is installed. ```twig {{ '2019-08-07 23:39:12'|format_datetime() }} ``` -------------------------------- ### Install CssInlinerExtension Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/inline_css.rst The inline_css filter requires the CssInlinerExtension. Install it using Composer. For Symfony projects, also install the extra-bundle. ```bash $ composer require twig/cssinliner-extra ``` ```bash $ composer require twig/extra-bundle ``` -------------------------------- ### Twig Inline Comment Example Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Demonstrates the use of inline comments in Twig templates. Comments start with # and extend to the end of the line. ```twig {{ "Hello World"|upper # this is an inline comment }} ``` -------------------------------- ### Operator Precedence Example Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Shows how Twig converts expressions to PHP based on operator precedence. It demonstrates the default conversion and how to alter precedence using parentheses. ```twig {{ 6 b-and 2 or 6 b-and 16 }} {# it is converted to the following PHP code: (6 & 2) || (6 & 16) #} {% set greeting = 'Hello ' %} {% set name = 'Fabien' %} {{ greeting ~ name|lower }} {# Hello fabien #} {# use parenthesis to change precedence #} {{ (greeting ~ name)|lower }} {# hello fabien #} ``` -------------------------------- ### Arrow Function Examples Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Illustrates the use of arrow functions (=>) for creating concise anonymous functions. Examples show their use with filters and how to store them in variables. ```twig {{ people|map(p => p.first_name)|join(', ') }} {% set first_name_fn = (p) => p.first_name %} {{ people|map(first_name_fn)|join(', ') }} ``` -------------------------------- ### Spread Operator Examples Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Shows how to use the spread operator (...) to expand sequences or mappings when creating new ones, and to expand arguments for function calls. ```twig {% set numbers = [1, 2, ...moreNumbers] %} {% set ratings = {'q1': 10, 'q2': 5, ...moreRatings} %} {{ 'Hello %s %s!'|format(...['Fabien', 'Potencier']) }} ``` -------------------------------- ### Slicing a string omitting start argument Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/slice.rst Shows how to slice a string from the beginning by omitting the start argument in the [] operator. ```twig {{ '12345'[:2] }} {# will display "12" #} ``` -------------------------------- ### Twig: Math Operations Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Provides examples of basic arithmetic operations supported in Twig templates. ```twig {{ 1 + 1 }} ``` ```twig {{ 3 - 2 }} ``` ```twig {{ 1 / 2 }} ``` ```twig {{ 11 % 7 }} ``` ```twig {{ 20 // 7 }} ``` ```twig {{ -20 // 7 }} ``` ```twig {{ 2 * 2 }} ``` ```twig {{ 2 ** 3 }} ``` ```twig {{ -1**0 }} ``` -------------------------------- ### Add IntlExtension Explicitly to Twig Environment Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/currency_symbol.rst Example of how to manually add the IntlExtension to the Twig environment if not using the extra bundle. ```php use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension()); ``` -------------------------------- ### Registering Runtime Extensions with Attributes Source: https://github.com/twigphp/twig/blob/3.x/doc/advanced.rst If extension methods are not static, register the class as a runtime extension using a runtime loader. This example shows how to register a class with a constructor dependency. ```php use Twig\Attribute\AsTwigFunction; class ProjectExtension { // Inject hypothetical dependencies public function __construct(private LipsumProvider $lipsumProvider) {} #[AsTwigFunction('lipsum')] public function lipsum(int $count): string { return $this->lipsumProvider->lipsum($count); } } $twig = new \Twig\Environment($loader); $twig->addExtension(new \Twig\Extension\AttributeExtension(ProjectExtension::class); $twig->addRuntimeLoader(new \Twig\RuntimeLoader\FactoryLoader([ ProjectExtension::class => function () use ($lipsumProvider) { return new ProjectExtension($lipsumProvider); }, ])); ``` -------------------------------- ### Twig String Starts With Operator Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Checks if a string begins with a specified substring. ```twig {% if 'Fabien' starts with 'F' %} {% endif %} ``` -------------------------------- ### Basic Range Source: https://github.com/twigphp/twig/blob/3.x/doc/functions/range.rst Generates a sequence of integers from a start to an end value. ```twig {% for i in range(0, 3) %} {{ i }}, {% endfor %} {# outputs 0, 1, 2, 3, #} ``` -------------------------------- ### Twig Reduce Filter with Initial Value Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/reduce.rst Shows how to use the reduce filter with an initial value. The second argument to the filter sets the starting point for the accumulation. ```twig {{ numbers|reduce((carry, value, key) => carry + value * key, 10) }} {# output 18 #} ``` -------------------------------- ### Get Locale Name in Specified Locale Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/locale_name.rst Returns the locale name translated into a specified locale. Ensure the IntlExtension is installed. ```twig {# allemand #} {{ 'de'|locale_name('fr') }} ``` ```twig {# français (Canada) #} {{ 'fr_CA'|locale_name('fr_FR') }} ``` -------------------------------- ### Get Template Content Source: https://github.com/twigphp/twig/blob/3.x/doc/functions/source.rst Use the 'source' function to retrieve the raw content of a template file. Pass the template name as an argument. ```twig {{ source('template.html.twig') }} {{ source(some_var) }} ``` -------------------------------- ### Twig Extension Functional Test Setup Source: https://github.com/twigphp/twig/blob/3.x/doc/advanced.rst Sets up a functional test for a Twig extension using the IntegrationTestCase. This involves defining the extensions and specifying the directory for fixture files. ```php namespace Project\Tests; use Twig\Test\IntegrationTestCase; class IntegrationTest extends IntegrationTestCase { public function getExtensions() { return [ new CustomTwigExtension1(), new CustomTwigExtension2(), ]; } public function getFixturesDir() { return __DIR__.'/Fixtures/'; } } ``` -------------------------------- ### Get Locale Name in Default Locale Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/locale_name.rst Returns the locale name using the current locale. Ensure the IntlExtension is installed. ```twig {# German #} {{ 'de'|locale_name }} ``` -------------------------------- ### Using expressions for slice arguments Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/slice.rst Illustrates using variables or expressions for the start and length arguments of the slice filter. ```twig {% for i in [1, 2, 3, 4, 5]|slice(start, length) %} {# ... #} {% endfor %} ``` -------------------------------- ### Registering a Twig Extension Source: https://github.com/twigphp/twig/blob/3.x/doc/api.rst Register a custom or built-in Twig extension using the addExtension() method. The SandboxExtension is shown as an example. ```php $twig->addExtension(new \Twig\Extension\SandboxExtension()); ``` -------------------------------- ### Get Currency Names with Specific Locale Source: https://github.com/twigphp/twig/blob/3.x/doc/functions/currency_names.rst This snippet shows how to retrieve currency names for a specific locale, in this case, French ('fr'). The results are formatted similarly to the default locale example. ```twig {# afghani (1927–2002), afghani afghan, ... #} {{ currency_names('fr')|join(', ') }} ``` -------------------------------- ### FilesystemLoader with a single directory Source: https://github.com/twigphp/twig/blob/3.x/doc/api.rst Initialize the FilesystemLoader to load templates from a specified directory. ```php $loader = new \Twig\Loader\FilesystemLoader($templateDir); ``` -------------------------------- ### Ternary Operator Examples Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Demonstrates the usage of the ternary operator for conditional expressions. It shows the standard form, a shorthand for when the condition and the true value are the same, and a shorthand for when the false value is an empty string. ```twig {{ result ? 'yes' : 'no' }} {{ result ?: 'no' }} is the same as {{ result ? result : 'no' }} {{ result ? 'yes' }} is the same as {{ result ? 'yes' : '' }} ``` -------------------------------- ### Rendering Templates Source: https://github.com/twigphp/twig/blob/3.x/doc/api.rst Illustrates how to render a loaded template with variables, both directly and via the environment. ```APIDOC ## Rendering Templates ### Description This section covers rendering templates with variables, either from a loaded template object or directly through the Twig environment. ### Method - `render(array $context = [])` on \Twig\TemplateWrapper - `render(string $name, array $context = [])` on \Twig\Environment - `renderBlock(string $name, array $context = [])` on \Twig\TemplateWrapper ### Endpoint N/A (PHP API) ### Parameters #### TemplateWrapper::render() - **context** (*array*) - Required - An associative array of variables to pass to the template. #### Environment::render() - **name** (*string*) - Required - The name of the template to load and render. - **context** (*array*) - Required - An associative array of variables to pass to the template. #### TemplateWrapper::renderBlock() - **name** (*string*) - Required - The name of the block to render. - **context** (*array*) - Required - An associative array of variables to pass to the template. ### Request Example ```php // Rendering a loaded template echo $template->render(['the' => 'variables', 'go' => 'here']); // Rendering directly via environment echo $twig->render('index.html.twig', ['the' => 'variables', 'go' => 'here']); // Rendering a specific block echo $template->renderBlock('block_name', ['the' => 'variables', 'go' => 'here']); ``` ### Response #### Success Response - **Output** (*string*) - The rendered HTML content of the template or block. ``` -------------------------------- ### Configure Twig Environment Source: https://github.com/twigphp/twig/blob/3.x/doc/api.rst Sets up a Twig environment with a filesystem loader and a compilation cache directory. Ensure the autoloader is included. ```php 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', ]); ``` -------------------------------- ### Assignment Operator Examples Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Demonstrates the assignment operator (=) for assigning values to variables within expressions. It covers simple assignments, chained assignments, and assignments within other expressions. ```twig {# assign #} {% do b = 1 + 3 %} {# assign and output the result #} {{ b = 1 + 3 }} {# assignments can be chained #} {% do a = b = 'foo' %} {# assignment can be used inside other expressions #} {% do a = (b = 4) + 5 %} ``` -------------------------------- ### Destructuring Assignment Example Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Demonstrates destructuring assignment using the '=' operator to extract values from sequences and assign them to variables in a single operation. ```twig {# returns the full user object, allowing chained access #} ``` -------------------------------- ### FilesystemLoader addPath and prependPath Source: https://github.com/twigphp/twig/blob/3.x/doc/api.rst Dynamically add or prepend template directories to the FilesystemLoader. ```php $loader->addPath($templateDir3); $loader->prependPath($templateDir4); ``` -------------------------------- ### Get all language names Source: https://github.com/twigphp/twig/blob/3.x/doc/functions/language_names.rst This snippet shows how to get a comma-separated string of all available language names using the default locale. ```twig {# Abkhazian, Achinese, ... #} {{ language_names()|join(', ') }} ``` -------------------------------- ### Include with 'only' Keyword Source: https://github.com/twigphp/twig/blob/3.x/doc/tags/include.rst Includes 'template.html.twig' while restricting variable access. The first example only allows 'name', and the second allows no variables from the parent context. ```twig {# only the name variable will be accessible #} {% include 'template.html.twig' with {'name': 'Fabien'} only %} {# no variables will be accessible #} {% include 'template.html.twig' only %} ``` -------------------------------- ### Using a global object method for lipsum generation Source: https://github.com/twigphp/twig/blob/3.x/doc/advanced.rst Demonstrates calling a method on a global object ('text') to generate lorem ipsum text. ```twig {{ text.lipsum(40) }} ``` -------------------------------- ### Get First Element of an Array Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/first.rst Use the 'first' filter to get the first item from an array. This works for numerical or associative arrays. ```twig {{ [1, 2, 3, 4]|first }} {# outputs 1 #} ``` -------------------------------- ### Creating a Basic Twig Filter Source: https://github.com/twigphp/twig/blob/3.x/doc/advanced.rst Demonstrates the instantiation of a TwigFilter object with a name, a callable, and an options array. ```php $filter = new \Twig\TwigFilter('rot13', 'str_rot13', $options); ``` -------------------------------- ### Get Timezone Name (Specific Locale) Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/timezone_name.rst Pass an explicit locale code to the timezone_name filter to get the timezone name in a specific language. ```twig {# heure du Pacifique nord-américain (Los Angeles) #} {{ 'America/Los_Angeles'|timezone_name('fr') }} ``` -------------------------------- ### FilesystemLoader with multiple directories Source: https://github.com/twigphp/twig/blob/3.x/doc/api.rst Configure the FilesystemLoader to search for templates across multiple directories, with a fallback mechanism. ```php $loader = new \Twig\Loader\FilesystemLoader([$templateDir1, $templateDir2]); ``` -------------------------------- ### Get Currency Symbol for EUR and JPY Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/currency_symbol.rst Demonstrates how to use the currency_symbol filter to get the symbols for EUR and JPY using the default locale. ```twig {# € #} {{ 'EUR'|currency_symbol }} {# ¥ #} {{ 'JPY'|currency_symbol }} ``` -------------------------------- ### FilesystemLoader with relative paths and getcwd Source: https://github.com/twigphp/twig/blob/3.x/doc/api.rst Initialize FilesystemLoader using relative paths and getcwd for cache key independence. Twig defaults to getcwd() for relative paths if the root path is not provided. ```php $loader = new \Twig\Loader\FilesystemLoader('templates', getcwd().'/..'); ``` -------------------------------- ### Get Currency Symbol for JPY with Specific Locale Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/currency_symbol.rst Shows how to use the currency_symbol filter with an explicit locale ('fr') to get the currency symbol for JPY. ```twig {# ¥ #} {{ 'JPY'|currency_symbol('fr') }} ``` -------------------------------- ### Implementing __get and __isset for Dynamic Properties Source: https://github.com/twigphp/twig/blob/3.x/doc/recipes.rst Shows how to implement the magic __get and __isset methods in a PHP class to allow Twig to access dynamically generated properties. ```php class Article { public function __get($name) { if ('title' == $name) { return 'The title'; } // throw some kind of error } public function __isset($name) { if ('title' == $name) { return true; } return false; } } ``` -------------------------------- ### Registering Undefined Function Callback Source: https://github.com/twigphp/twig/blob/3.x/doc/recipes.rst Shows how to register a callback to dynamically define Twig functions that are not explicitly registered. This example demonstrates auto-registering native PHP functions, but should be used with caution due to security implications. ```php $twig->registerUndefinedFunctionCallback(function ($name) { if (function_exists($name)) { return new \Twig\TwigFunction($name, $name); } return false; }); ``` -------------------------------- ### Get script names for the current locale Source: https://github.com/twigphp/twig/blob/3.x/doc/functions/script_names.rst Call script_names() without arguments to get script names for the default locale. The output is then joined into a comma-separated string. ```twig {# Adlam, Afaka, ... #} {{ script_names()|join(', ') }} ``` -------------------------------- ### Load Template from String Source: https://github.com/twigphp/twig/blob/3.x/doc/functions/template_from_string.rst Demonstrates loading a simple template from a string using template_from_string. ```twig {{ include(template_from_string("Hello {{ name }}")) }} {{ include(template_from_string(page.template)) }} ``` -------------------------------- ### Basic Cycle Usage Source: https://github.com/twigphp/twig/blob/3.x/doc/functions/cycle.rst Demonstrates the basic usage of the cycle function to alternate between 'odd' and 'even' strings based on the loop index. ```twig {% set start_year = date() | date('Y') %} {% set end_year = start_year + 5 %} {% for year in start_year..end_year %} {{ cycle(['odd', 'even'], loop.index0) }} {% endfor %} ``` -------------------------------- ### Get Currency Names with Default Locale Source: https://github.com/twigphp/twig/blob/3.x/doc/functions/currency_names.rst This snippet demonstrates how to get all currency names using the default locale. The output is joined by a comma and space for readability. ```twig {# Afghan Afghani, Afghan Afghani (1927–2002), ... #} {{ currency_names()|join(', ') }} ``` -------------------------------- ### Get Timezone Name (Default Locale) Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/timezone_name.rst Use the timezone_name filter to get the timezone name for a given ISO 8601 identifier using the current locale. ```twig {# Central European Time (Paris) #} {{ 'Europe/Paris'|timezone_name }} {# Pacific Time (Los Angeles) #} {{ 'America/Los_Angeles'|timezone_name }} ``` -------------------------------- ### Include Function vs. Include Statement Source: https://github.com/twigphp/twig/blob/3.x/doc/tags/include.rst Demonstrates storing rendered template content in a variable using both the 'include' function and statement. ```twig {# Store a rendered template in a variable #} {% set content %} {% include 'template.html.twig' %} {% endset %} {# vs #} {% set content = include('template.html.twig') %} ``` -------------------------------- ### Get Current Date for Comparison Source: https://github.com/twigphp/twig/blob/3.x/doc/functions/date.rst Compares a user's creation date with the current date. This snippet demonstrates how to get the current date using the date function without arguments. ```html+twig {% if date(user.created_at) < date() %} {# always! #} {% endif %} ``` -------------------------------- ### Twig Embed Tag Usage Examples Source: https://github.com/twigphp/twig/blob/3.x/doc/tags/embed.rst Demonstrates various ways to use the Twig embed tag, including passing variables, using the 'only' modifier, and ignoring missing templates. The embed tag takes the same arguments as the include tag. ```twig {% embed "base" with {'name': 'Fabien'} %} ... {% endembed %} ``` ```twig {% embed "base" with {'name': 'Fabien'} only %} ... {% endembed %} ``` ```twig {% embed "base" ignore missing %} ... {% endembed %} ``` -------------------------------- ### Get Last Value of a Mapping Source: https://github.com/twigphp/twig/blob/3.x/doc/filters/last.rst Apply the 'last' filter to a mapping (associative array) to get the value associated with the last key. This works for retrieving the final entry in an object-like structure. ```twig {{ {a: 1, b: 2, c: 3, d: 4}|last }} {# outputs 4 #} ``` -------------------------------- ### Enabling Sandbox Globally Source: https://github.com/twigphp/twig/blob/3.x/doc/sandbox.rst Enable sandbox mode for all templates by passing true as the second argument to the SandboxExtension constructor. ```php $twig->addExtension(new \Twig\Extension\SandboxExtension($policy, true)); ``` -------------------------------- ### Basic Twig Template Structure Source: https://github.com/twigphp/twig/blob/3.x/doc/templates.rst Illustrates fundamental Twig syntax including HTML structure, for-loops for iterating over data, and variable output. ```html+twig