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 Steps

  1. Installation:

    composer require twig/intl-extra
    

    Register the extension in Laravel’s Twig service provider (e.g., AppServiceProvider):

    use Twig\Extra\Intl\IntlExtension;
    
    public function boot()
    {
        $this->app['twig']->addExtension(new IntlExtension());
    }
    
  2. First Use Case: Format a currency in a Twig template (e.g., resources/views/emails/invoice.twig):

    {{ 1000.50|format_currency('USD') }}  {# Output: $1,000.50 #}
    

    Or format a date for a user’s locale:

    {{ now|format_datetime('medium', 'fr_FR') }}  {# Output: 20 mai 2024 à 14:30:00 #}
    
  3. Where to Look First:

    • Laravel-Twig Bridge: Use twig/bridge if integrating Twig with Laravel’s service container.
      composer require twig/bridge
      
      Configure in config/twig.php:
      'bridge' => [
          'enabled' => true,
      ],
      
    • Locale Configuration: Ensure your app’s locale (e.g., app()->getLocale()) aligns with Twig’s expectations. Override per-template if needed:
      {% set locale = 'ja_JP' %}
      {{ '2024-05-20'|format_date('full') }}  {# 2024年5月20日 (月曜日) #}
      

Implementation Patterns

Core Usage Patterns

1. Locale-Aware Formatting

  • Numbers/Currencies:
    {{ 1234.56|format_number(2, 'de_DE') }}  {# 1.234,56 #}
    {{ 1000|format_currency('EUR', 'de_DE') }}  {# 1.000,00 € #}
    
  • Dates/Times:
    {{ '2024-05-20T14:30:00'|format_datetime('long', 'en_US') }}
    {# May 20, 2024 at 2:30:00 PM GMT+2 #}
    

2. Dynamic Locale Switching

  • Pass the user’s locale from Laravel to Twig (e.g., via a template variable):
    // Controller
    return view('dashboard', ['userLocale' => $user->locale]);
    
    {% set locale = userLocale %}
    {{ 1000|format_currency('GBP') }}  {# £1,000 (if locale=en_GB) #}
    

3. Pluralization and Selectors

  • Handle gender/quantity-specific text:
    {{ 1|pluralize('item', 'items') }}  {# item #}
    {{ 2|pluralize('item', 'items') }}  {# items #}
    
    {{ 1|select('one', 'two', 'few', 'many', 'other') }}
    {# 'one' #}
    

4. Timezone Handling

  • Convert timestamps to user timezones:
    {{ '2024-05-20T14:30:00+00:00'|timezone('America/New_York')|format_datetime('short') }}
    {# 5/20/24, 10:30 AM #}
    
  • List timezones for a country:
    {{ 'US'|country_timezones }}
    {# ['America/New_York', 'America/Chicago', ...] #}
    

5. Fallbacks and Defaults

  • Use default filter for unsupported locales:
    {{ '2024-05-20'|format_date('full', 'xx_XX', 'en_US') }}
    {# Falls back to 'en_US' if 'xx_XX' is invalid #}
    

Integration Tips

Laravel-Specific Patterns

  1. Blade + Twig Hybrid:

    • Use Twig for complex formatting in Blade templates via @twig directives:
      @twig
          {{ '1000'|format_currency('USD') }}
      @endtwig
      
    • Requires twig/bridge and configuring Blade to parse Twig syntax.
  2. API Responses:

    • Format data in Twig before returning JSON (e.g., for localized APIs):
      $response = view('api.response', ['data' => $data])->render();
      return response()->json(['formatted' => $response]);
      
  3. Mailables:

    • Leverage Twig for email templates with dynamic locales:
      // In a Mailable
      $this->with(['locale' => $user->locale]);
      
      {% set locale = locale %}
      {{ order.total|format_currency('EUR') }}
      
  4. Testing:

    • Mock locales in tests:
      $twig = new \Twig\Environment($loader);
      $twig->addExtension(new IntlExtension());
      $twig->addGlobal('locale', 'fr_FR');
      
    • Test edge cases (e.g., unsupported locales):
      $this->assertEquals('$1,000.00', $twig->render('{{ 1000|format_currency("USD") }}'));
      

Performance Patterns

  1. Cache Compiled Templates:
    • Enable Twig’s cache in config/twig.php:
      'cache' => env('APP_DEBUG') ? false : storage_path('framework/views'),
      
  2. Pre-Format Data:
    • Format data in PHP (e.g., using NumberFormatter) and pass to Twig for consistency:
      $formatter = new \NumberFormatter('de_DE', \NumberFormatter::CURRENCY);
      $formatted = $formatter->format($amount);
      return view('dashboard', ['amount' => $formatted]);
      
  3. Avoid Heavy Filters in Loops:
    • Replace:
      {% for item in items %}
          {{ item.price|format_currency('EUR') }}  {# Expensive in loops #}
      {% endfor %}
      
    • With:
      // Controller
      $formattedItems = array_map(fn($item) => formatCurrency($item->price, 'EUR'), $items);
      return view('items', ['items' => $formattedItems]);
      

Gotchas and Tips

Pitfalls

  1. Locale Mismatch:

    • Issue: Twig’s locale may override Laravel’s app locale.
      {% set locale = 'fr_FR' %}
      {{ now|format_datetime('short') }}  {# Uses 'fr_FR', not app()->getLocale() #}
      
    • Fix: Bind Twig’s locale to Laravel’s:
      $twig->addFunction(new \Twig\TwigFunction('app_locale', function() {
          return app()->getLocale();
      }));
      
      Then use:
      {% set locale = app_locale() %}
      
  2. Intl Extension Missing:

    • Issue: Silent failures if intl extension is disabled.
    • Fix: Check in php.ini or runtime:
      if (!extension_loaded('intl')) {
          throw new \RuntimeException('Intl extension is required for Twig Intl filters.');
      }
      
  3. Caching Quirks:

    • Issue: Twig’s cache may not invalidate if locales change dynamically.
    • Fix: Clear cache when locales are updated:
      \Artisan::call('twig:clear');
      
  4. Blade Integration Complexity:

    • Issue: @twig directives in Blade can bloat templates and reduce readability.
    • Fix: Use Twig for entire templates (e.g., emails) or create a custom Blade directive wrapper.
  5. Unsupported Locales:

    • Issue: Some locales (e.g., xx_XX) may not work.
    • Fix: Validate locales in PHP before passing to Twig:
      $locale = Locale::canonicalize($userLocale);
      if (Locale::getRegion($locale) === null) {
          $locale = app()->getFallbackLocale();
      }
      
  6. Timezone Ambiguity:

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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata