Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Intl Extra Laravel Package

twig/intl-extra

Twig Intl Extra adds internationalization helpers to Twig: look up country, currency, language, locale and timezone names, list country timezones, and format numbers, currencies, dates and times using ICU/Intl-style formatting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require twig/intl-extra
    

    Add the extension to your Twig environment in Laravel:

    // config/twig.php (or in your service provider)
    $twig->addExtension(new \Twig\Extra\Intl\IntlExtension());
    
  2. First Use Case: Format a date in a Twig template:

    {{ '2024-05-20'|date('full', 'en_US') }}
    

    Output: Monday, May 20, 2024

  3. Where to Look First:

    • Twig Intl Docs (official reference).
    • GitHub Issues for edge cases.
    • vendor/twig/twig/src/Extra/Intl/ for extension source (if customizing).

Implementation Patterns

Common Workflows

  1. Localization:

    • Format numbers/currencies with locale awareness:
      {{ 1234.56|number_format(2, 'en_US') }}  {# 1,234.56 #}
      {{ 1234.56|number_format(2, 'de_DE') }}  {# 1.234,56 #}
      
    • Pluralize dynamically:
      {{ 5|pluralize('item', 'items') }}  {# items #}
      
  2. Date/Time Handling:

    • Relative time (e.g., "2 days ago"):
      {{ '2024-05-18'|relative_date('en_US') }}
      
    • Timezone-aware formatting:
      {{ now|date('medium', 'Europe/Paris') }}
      
  3. Text Processing:

    • Unicode-aware sorting:
      {% set sorted = ['résumé', 'apple', 'banana']|sort %}
      
    • Transliteration (e.g., for URLs):
      {{ 'résumé'|transliterate }}
      
  4. Integration with Laravel:

    • Blade + Twig: Use BladeOne or twigblade/twig-bridge to mix Twig filters in Blade:
      // In a Blade view:
      @twig('{{ date|date("full", "en_US") }}')
      
    • Form Requests: Validate locale-specific formats:
      use Twig\Extra\Intl\IntlExtension;
      
      $validator->extend('locale_date', function ($attribute, $value, $parameters, $validator) {
          $intl = new IntlExtension();
          return $intl->getDateFormatter($parameters[0], $parameters[1])->parse($value) !== false;
      });
      
  5. Dynamic Locale Switching:

    • Store user locale in session and pass to Twig:
      // In a middleware/service
      $twig->addGlobal('locale', session('locale', 'en_US'));
      
      {{ 1234|number_format(2, locale) }}
      

Gotchas and Tips

Pitfalls

  1. ICU Extension Dependency:

    • Requires PHP’s intl extension (not enabled by default on some hosts).
    • Verify with:
      php -m | grep intl
      
    • Fix: Enable in php.ini or use a Docker image with intl pre-installed (e.g., php:8.2-cli-intl).
  2. Locale Fallbacks:

    • Missing locales (e.g., zh_Hant_TW) throw errors. Use fallbacks:
      {{ '2024-05-20'|date('full', 'zh_Hant_TW', 'zh_Hans_CN') }}
      
    • Tip: Cache resolved locales in a service:
      $fallbackLocales = [
          'zh_Hant_TW' => 'zh_Hans_CN',
          'en_GB' => 'en_US',
      ];
      
  3. Performance:

    • Date/Number Formatting: Expensive operations. Cache formatters:
      $formatter = $intlExtension->getDateFormatter('full', 'en_US');
      // Reuse $formatter in multiple templates.
      
    • Avoid in Loops: Intl functions are not loop-optimized. Pre-process data in PHP.
  4. Twig Caching:

    • Disable caching for dynamic locales:
      $twig->setCache(false); // Or use a per-locale cache key.
      
  5. Blade Integration Quirks:

    • Escaping: Twig filters escape output by default. Use |raw if needed:
      @twig('{{ "script"|raw }}')
      
    • Syntax Conflicts: Avoid | in Blade attributes (e.g., {{ date|date('full') }} may break). Use @twig blocks.

Debugging Tips

  1. Check ICU Data:

    • List available locales:
      php -r "print_r(\IntlDateFormatter::getAvailableLocales());"
      
    • Verify ICU version:
      php -r "echo \IntlBreakIterator::getICUVersion();"
      
  2. Fallback Logic:

    • Debug missing locales with:
      {% set formatter = _intl.getDateFormatter('full', 'unknown_locale') %}
      {% if formatter is null %}
          Locale not supported! Falling back to 'en_US'.
      {% endif %}
      
  3. Custom Extensions:

    • Extend the IntlExtension class to add Laravel-specific filters:
      class LaravelIntlExtension extends \Twig\Extra\Intl\IntlExtension {
          public function getFunctions() {
              return array_merge(parent::getFunctions(), [
                  new \Twig\TwigFunction('laravel_pluralize', [$this, 'laravelPluralize']),
              ]);
          }
      
          public function laravelPluralize($count, $singular, $plural) {
              return parent::pluralize($count, $singular, $plural);
          }
      }
      

Extension Points

  1. Custom Formatters:

    • Override default formatters (e.g., for API responses):
      $twig->addFunction(new \Twig\TwigFunction('api_date', function ($date) {
          return (new \DateTime($date))->format('Y-m-d\TH:i:sP');
      }));
      
  2. Locale Provider:

    • Replace the hardcoded locale logic with a Laravel service:
      $twig->addFunction(new \Twig\TwigFunction('get_locale', function () {
          return app(\App\Services\LocaleService::class)->get();
      }));
      
  3. Testing:

    • Mock IntlExtension in tests:
      $intl = $this->createMock(\Twig\Extra\Intl\IntlExtension::class);
      $intl->method('pluralize')->willReturn('items');
      $twig->addExtension($intl);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4