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 your Laravel Twig environment (e.g., in AppServiceProvider):

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

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

    Or use it in a Blade template via Twig bridge (if configured):

    @twig
        {{ 1000.50|format_currency('EUR') }}
    @endtwig
    
  3. Where to Look First:

    • Laravel Twig Integration: Check if using twig/bridge or standalone Twig.
    • Locale Configuration: Ensure app()->getLocale() aligns with template needs (e.g., config/app.php).
    • Intl Extension: Verify intl is enabled (php -m | grep intl).
    • Documentation: Focus on Twig Intl Filters.

Implementation Patterns

Core Usage Patterns

1. Locale-Aware Formatting

  • Numbers/Currencies:
    {{ 1234567.89|format_currency('JPY') }}  {# ¥1,234,568 #}
    {{ 1234567.89|number_format(2, 'de_DE') }}  {# 1.234.567,89 #}
    
  • Dates/Times:
    {{ '2024-12-25'|date('full', 'fr_FR') }}  {# mercredi 25 décembre 2024 #}
    {{ now|relative_date('en_US') }}  {# "2 hours ago" #}
    

2. Dynamic Locale Switching

  • Bind Twig locale to Laravel’s app locale:
    // In service provider
    $twig->addFunction(new \Twig\TwigFunction('app_locale', function() {
        return app()->getLocale();
    }));
    
    {{ 'Hello'|trans({ 'locale': app_locale() }) }}
    

3. Pluralization and Selectors

  • Plurals:
    {{ 1|pluralize('apple', 'apples') }}  {# apple #}
    {{ 5|pluralize('apple', 'apples') }}  {# apples #}
    
  • Selectors (e.g., for gendered translations):
    {{ 'user'|select('male', 'female', 'other') }}
    

4. Country/Timezone Lookups

  • Country Names:
    {{ 'US'|country_name('en_US') }}  {# United States #}
    
  • Timezones:
    {{ 'America/New_York'|timezone_name('en_US') }}  {# Eastern Time #}
    {{ 'US'|country_timezones('en_US') }}  {# ['America/New_York', 'America/Chicago', ...] #}
    

5. Integration with Laravel Ecosystem

  • Carbon Integration: Pass a Carbon instance to Twig:
    return view('twig-template', ['event' => Carbon::now()]);
    
    {{ event|format_datetime('full', 'es_ES') }}
    
  • Form Requests: Use in forms for locale-aware validation messages:
    {{ form_errors|trans({'locale': request.locale}) }}
    

6. Caching Strategies

  • Cache compiled Twig templates with Intl filters:
    $twig->setCache(new \Twig\Cache\FilesystemCache('/path/to/cache'));
    
  • Pre-format data in PHP for complex templates:
    $formattedPrice = number_format($price, 2, '.', ',');
    return view('twig-template', compact('formattedPrice'));
    

7. Testing

  • Mock locales in tests:
    $twig = new \Twig\Environment($loader);
    $twig->addExtension(new IntlExtension());
    $twig->setLocale('fr_FR'); // Force French for tests
    
  • Test edge cases:
    {{ 'ZZ'|country_name('en_US') }}  {# Should handle invalid codes #}
    

Workflows

Workflow 1: Localized E-Commerce Pricing

  1. Controller:
    return view('product', [
        'price' => 999.99,
        'currency' => 'EUR',
    ]);
    
  2. Twig Template:
    <h1>{{ product.name }}</h1>
    <p>Price: {{ price|format_currency(currency) }}</p>
    <p>Formatted: {{ price|number_format(2, app_locale()) }}</p>
    

Workflow 2: User Dashboard with Timezones

  1. Middleware: Set user’s timezone in the request:
    $request->merge(['timezone' => auth()->user()->timezone]);
    
  2. Twig Template:
    <p>Last login: {{ user.last_login|format_datetime('medium', request.timezone) }}</p>
    

Workflow 3: Multilingual Admin Panel

  1. Route:
    Route::get('/admin', function() {
        return view('admin', ['locale' => 'es_ES']);
    })->middleware('locale');
    
  2. Twig Template:
    {% set locale = 'es_ES' %}
    <h1>{{ 'Dashboard'|trans({'locale': locale}) }}</h1>
    <p>{{ 1000|number_format(0, locale) }}</p>
    

Workflow 4: Email Notifications

  1. Mailable:
    public function build()
    {
        return $this->markdown('emails.order-confirmation')
                    ->with([
                        'order' => $this->order,
                        'locale' => $this->user->locale,
                    ]);
    }
    
  2. Twig Email Template:
    <p>Order #{{ order.id }} total: {{ order.total|format_currency('USD') }}</p>
    <p>Placed on: {{ order.created_at|format_date('medium', locale) }}</p>
    

Integration Tips

  1. Blade + Twig Hybrid: Use @twig directives in Blade for Intl-Extra features:

    @twig
        {{ $price|format_currency('GBP') }}
    @endtwig
    
  2. Laravel Nova Customization: Extend Nova’s Twig templates (e.g., resources/views/vendor/nova/) to use Intl-Extra:

    {{ resource.createdAt|format_datetime('medium', resource.locale) }}
    
  3. API Responses with Twig: Use Twig to format API responses (e.g., for GraphQL or JSON:API):

    $response = new TwigResponse($twig->render('api/response.twig', [
        'data' => $data,
        'locale' => $request->locale,
    ]), 200, ['Content-Type' => 'application/json']);
    
  4. Livewire + Twig: Pass data to Livewire components and format in Twig:

    public $price = 199.99;
    public $currency = 'USD';
    
    <div>{{ this.price|format_currency(this.currency) }}</div>
    
  5. Inertia.js: Use Twig for server-side rendering of Inertia pages:

    return Inertia::render('Dashboard', [
        'stats' => $stats,
    ])->withViewData(['twig' => $twig]);
    
    <!-- resources/js/Pages/Dashboard.vue -->
    <template>
        <div>{{ $page.props.stats.revenue|format_currency('EUR') }}</div>
    </template>
    

Gotchas and Tips

Pitfalls

  1. **Locale M
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope