The Intl extension is an extension for Twig that adds the localizeddate
, localizednumber
and localizedcurrency
filters. How can I install and set up the extension so that I can use those filters in my Twig templates?
Twig is a template framework and is a direct replacement for PHP template. Twig extension provides more flexibility to process almost anything inside twig. Twig extends in many ways such as tags, filters, operators, global variables, and functions.
The Internationalization extension (Intl) is a wrapper for the ICU library, a set of C/C++ and Java libraries that provide Unicode and Globalization support for software applications. It enables PHP programmers to perform UCA-conformant collation and date/time/number/currency formatting in their scripts.
First of all, you will need the PHP intl extension, as the Twig extension is built on top of that. The Twig Intl extension will throw an Exception if the PHP intl extension is not enabled. Installation instructions can be found in the official PHP documentation.
On Ubuntu/Debian machines, this is as easy as running the following command:
sudo apt install php-intl
On Windows machines, you probably have to uncomment the following line in php.ini:
extension=php_intl.dll
For CentOS, or other architectures, follow the instructions here. Note that CentOS requires both PECL and the GCC C++ compiler to be installed: yum install php-pear
and yum install gcc-c++
.
Once the extension is added to php.ini, then restart the web server.
Next, you will need the Twig Extensions package (that contains the Intl extension, among others), which can be installed using Composer. Run this command in the command line:
composer require twig/extensions
This will add the dependency to your composer.json
and download it.
Note: the localizednumber
and localizedcurrency
filters were introduced in version 1.2.0, so you need at least that version if you want to use them.
If you are using Twig directly (i.e. not in a Symfony project), add the extension to the Twig environment manually:
<?php use Twig\Environment; use Twig\Extensions\IntlExtension; $twig = new Environment($loader); $twig->addExtension(new IntlExtension());
If you are using a Symfony application, you can add the extension to Twig by creating a service and tagging it as a Twig extension in config/services.yml
:
services: twig.extension.intl: class: Twig\Extensions\IntlExtension tags: - { name: twig.extension }
<?php Locale::setDefault('nl-NL');
In config/framework.yaml
, uncomment the default_locale
setting:
framework: default_locale: en
In Symfony 3/4/5, with the autoconfiguration feature enabled, it's as easy as registering the extension as a service:
// config/services.yaml services: … Twig\Extensions\IntlExtension: ~
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With