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

Twig I18N Extension Laravel Package

phpmyadmin/twig-i18n-extension

Twig extension that adds i18n helpers for phpMyAdmin and other Twig-based apps. Provides translation-related functions/filters to integrate localization into templates with minimal setup and overhead.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require phpmyadmin/twig-i18n-extension
    

    Add the extension to your Twig environment in config/app.php:

    'twig' => [
        'extensions' => [
            \phpmyadmin\Twig\I18nExtension::class,
        ],
    ],
    
  2. Basic Usage Register a translation domain in your config/app.php:

    'i18n' => [
        'domains' => [
            'app' => resource_path('lang'),
        ],
    ],
    

    Load translations in a Twig template:

    {% trans from 'app' %}Hello, {name}!{% endtrans %}
    

    Pass variables via PHP:

    return view('welcome', ['name' => 'John']);
    
  3. First Use Case Localize a simple greeting in a Laravel Blade template:

    <h1>{{ 'Welcome'|trans({'name': user.name}, 'app') }}</h1>
    

Implementation Patterns

Translation Workflows

  1. Domain-Based Isolation

    • Use multiple domains (e.g., app, admin, api) to organize translations by feature/module.
    • Example:
      {% trans from 'admin' %}Dashboard{% endtrans %}
      
  2. Dynamic Fallbacks

    • Chain domains for fallback translations:
      // config/app.php
      'i18n' => [
          'fallbacks' => ['app', 'admin', 'default'],
      ],
      
    • Twig usage:
      {{ 'Button'|trans({}, 'app') }} {# Falls back to 'admin' then 'default' #}
      
  3. Pluralization & Context

    • Handle plural forms in Twig:
      {% trans choice from 'app' %}
          {0} No items|{1} One item|{% plural %} {{ count }} items
      {% endtrans %}
      
    • Pass count via PHP:
      return view('items', ['count' => 5]);
      
  4. Interpolation

    • Use named placeholders:
      {% trans from 'app' %}User {username} logged in at {time}.{% endtrans %}
      
    • Pass data as an array:
      return view('dashboard', [
          'username' => 'john_doe',
          'time' => now()->format('H:i'),
      ]);
      

Integration with Laravel

  1. Locale Switching

    • Bind a middleware to update the locale:
      public function handle($request, Closure $next) {
          app()->setLocale($request->header('Accept-Language') ?? 'en');
          return $next($request);
      }
      
    • Use in Twig:
      {{ 'Language'|trans({}, 'app') }}: {{ app.locale }}
      
  2. Translation Loading

    • Load translations dynamically (e.g., from a database) by extending the Loader:
      use phpmyadmin\Twig\I18nExtension\Loader\FilesystemLoader;
      
      $loader = new FilesystemLoader(resource_path('lang'));
      $loader->addPath(resource_path('lang/db'), 'db');
      
  3. Blade Compatibility

    • Use @trans directive in Blade:
      @trans('app', 'Welcome, {name}!', ['name' => $user->name])
      
  4. Testing

    • Mock translations in PHPUnit:
      $this->app->singleton(\Illuminate\Translation\Translator::class, function () {
          $translator = new Translator($this->app['config']['app.locale'], $this->app['loader']);
          $translator->addNamespace('app', __DIR__.'/stubs/lang');
          return $translator;
      });
      

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts

    • Ensure translation files match the domain namespace (e.g., app/en/validation.php for domain app).
    • Fix: Verify config/app.php under 'i18n.domains' maps correctly to your resources/lang structure.
  2. Caching Issues

    • Laravel’s translation cache may not refresh automatically after adding new translations.
    • Fix: Run:
      php artisan config:clear
      php artisan view:clear
      
  3. Pluralization Rules

    • The extension uses ICU-style pluralization. Custom rules require extending the Pluralizer class.
    • Tip: For simple cases, use Laravel’s built-in pluralization helpers as a fallback.
  4. Performance with Large Domains

    • Loading many domains upfront can slow down Twig compilation.
    • Tip: Lazy-load domains or use a priority system.

Debugging

  1. Missing Translations

    • Check if the file exists at resources/lang/{locale}/{domain}.php.
    • Debug: Enable Twig’s debug mode:
      'twig' => [
          'debug' => env('APP_DEBUG', false),
      ],
      
  2. Syntax Errors in Twig

    • Invalid {% trans %} tags may silently fail. Use {{ 'key'|trans }} for errors.
    • Tip: Wrap translations in try-catch for graceful fallbacks:
      {% set translated = 'key'|trans({'domain': 'app'}, {'fallback': 'Default'}) %}
      
  3. Locale Fallbacks

    • If a translation is missing in en, it won’t fallback to another locale by default.
    • Fix: Configure fallbacks in config/app.php:
      'locale' => 'en',
      'fallback_locales' => ['en', 'fr', 'es'],
      

Extension Points

  1. Custom Loaders

    • Extend phpmyadmin\Twig\I18nExtension\Loader\LoaderInterface for database/API-based translations:
      class DatabaseLoader implements LoaderInterface {
          public function load($domain, $locale) {
              return Cache::remember("translations.{$domain}.{$locale}", 3600, function () {
                  return DB::table('translations')->where([
                      'domain' => $domain,
                      'locale' => $locale,
                  ])->pluck('content', 'key');
              });
          }
      }
      
  2. Filters & Tests

    • Add custom Twig filters/tests for translation logic:
      $twig->addFilter(new \Twig\TwigFilter('customTrans', function ($key, $params, $domain) {
          return app('translator')->get($domain, $key, $params);
      }));
      
  3. Override Pluralization

    • Replace the default pluralizer:
      $extension = new \phpmyadmin\Twig\I18nExtension\I18nExtension($loader, new CustomPluralizer());
      
  4. Integration with Laravel Mix

    • Compile translation files during build:
      mix.js('resources/js/app.js', 'public/js')
          .then(() => {
              require('fs').writeFileSync(
                  'resources/lang/en/compiled.php',
                  `<?php return ${JSON.stringify(require('./en.json'))};`
              );
          });
      
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views