Intl extension for Twig

Hi.

I wonder if there is a tutorial or guideline for dummies on how to install TWIG extensions? It would be helpful to know how to localize dates to format them in any language, for example. What I Googled looks pretty complex to understand if you are a non-coder.

Hello John,

Thank you for the inquiry.

You can refer to the documentation below.

– https://theme.co/docs/twig-api
– https://theme.co/docs/twig-api#custom-extensions

This might also help: https://twig.symfony.com/doc/3.x/advanced.html#creating-an-extension

For your situation, creating a Twig filter might be sufficient. Try adding this code to the functions.php file:

// Add a filter to tap into all filters
add_filter('cs_twig_filters', function ($results) {
    // Add a filter to be used as my_filter
    $results['x_localize_date'] = [
        'callable' => function ($value, $locale) {
            $timestamp = strtotime($value) * 1000;
            $calendar = IntlCalendar::createInstance(null, $locale);
            $calendar->setTime($timestamp);

            $formatter = new IntlDateFormatter($locale, IntlDateFormatter::LONG, IntlDateFormatter::NONE);
            return $formatter->format($calendar);
        }
    ];

    return $results;
});

In CS, you can use this filter in a Text element:

fr_FR: {{ "2025-03-28" | x_localize_date('fr_FR') }} 
en_US: {{ "2025-03-28" | x_localize_date('en_US') }}

Result:

fr_FR: 28 mars 2025
en_US: March 28, 2025

This is based on: https://www.sitepoint.com/localizing-dates-currency-and-numbers-with-php-intl/#calendars, https://www.the-art-of-web.com/php/intl-date-formatter/

Make sure that php-intl or php_intl.dll extension is enabled.

Let us know if you need more info.

Best regards.

1 Like

Just to add. We don’t add in the Twig Internationalization plugin because it uses a ton of files, and certain WordPress hosts limit the number of files you can have on your site.