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

I18N Bundle Laravel Package

dinecat/i18n-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require dinecat/i18n-bundle
    

    Register it in config/bundles.php:

    return [
        // ...
        Dinecat\I18nBundle\DinecatI18nBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Configure locales in config/packages/dinecat_i18n.yaml:

    dinecat_i18n:
        locales: ['en', 'fr', 'de']
        default_locale: 'en'
    
  3. First Use Case Translate a template variable in Twig:

    {{ 'Hello, %name%'|trans({'name': user.name}) }}
    

    Ensure translation files exist in translations/messages.{locale}.yml:

    # translations/messages.fr.yml
    "Hello, %name%": Bonjour, %name%
    

Implementation Patterns

1. Dynamic Locale Switching

  • Middleware Integration Use Symfony’s LocaleListener or create a custom middleware to set the locale via URL, session, or header:

    // src/EventListener/LocaleListener.php
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        $locale = $request->getPreferredLanguage(['en', 'fr', 'de']);
        $request->setLocale($locale);
    }
    
  • Route-Based Locale Configure routes to include locale prefixes:

    # config/routes.yaml
    _locale:
        resource: "@DinecatI18nBundle/Resources/config/routing/locale.yaml"
    

2. Data Translation

  • Entity Translation Use the bundle’s Translatable trait for Doctrine entities:

    use Dinecat\I18nBundle\Doctrine\ORM\Mapping\Annotation as I18n;
    
    /**
     * @I18n\TranslationDomain("messages")
     */
    class Product
    {
        /**
         * @I18n\Translatable
         */
        private $name;
    }
    

    Populate translations via CLI or admin panel.

  • Array/Data Translation Translate arrays/dictionaries in controllers:

    use Dinecat\I18nBundle\Translation\Translator;
    
    public function show(Translator $translator)
    {
        $data = ['greeting' => 'Hello'];
        $translated = $translator->trans($data, null, 'fr');
        // Returns ['greeting' => 'Bonjour']
    }
    

3. Twig Integration

  • Custom Filters Extend Twig with custom filters for nested translations:

    {% set user = {'name': 'John'} %}
    {{ 'Welcome, %name%!'|trans(user)|raw }}
    

    Register custom filters in twig.config.php:

    $twig->addFilter(new \Twig\TwigFilter('custom_trans', [$translator, 'trans']));
    
  • Translation Domains Use domains to separate translation scopes (e.g., validation, admin):

    {{ 'error.invalid'|trans({}, 'validation') }}
    

4. Fallback Logic

  • Hierarchical Fallbacks Configure fallback chains in config/packages/dinecat_i18n.yaml:
    dinecat_i18n:
        fallback_locales: ['en', 'fr']
    
    Ensures fr_CA falls back to fr then en.

Gotchas and Tips

Pitfalls

  1. Missing Translation Files

    • Symptom: No translation found for key errors.
    • Fix: Ensure files exist in translations/{domain}.{locale}.yml (e.g., messages.fr.yml).
    • Tip: Use php bin/console debug:translation to validate keys.
  2. Locale Not Persisting

    • Symptom: Locale resets after page reload.
    • Fix: Store locale in session or use middleware to reapply it:
      $request->getSession()->set('_locale', $locale);
      
  3. Doctrine Entity Translation Not Working

    • Symptom: @Translatable fields ignore locale changes.
    • Fix: Ensure:
      • The Translation entity is mapped correctly.
      • The Translatable trait is applied to the field, not the class.
      • The translation_domain is set (e.g., @TranslationDomain("products")).
  4. Caching Issues

    • Symptom: Translations not updating after changes.
    • Fix: Clear the cache:
      php bin/console cache:clear
      
    • Tip: Disable caching in dev environment for testing:
      # config/packages/dinecat_i18n.yaml
      dinecat_i18n:
          cache: false
      

Debugging Tips

  • Log Missing Translations Enable debug mode to log missing keys:

    # config/packages/monolog.yaml
    monolog:
        handlers:
            main:
                level: debug
                channels: ["!event"]
    
  • Inspect Translator Service Dump the translator’s loaded catalog:

    dump($translator->getCatalogue()->getLocale());
    

Extension Points

  1. Custom Translator Extend the translator to add logic (e.g., pluralization):

    use Dinecat\I18nBundle\Translation\Translator as BaseTranslator;
    
    class CustomTranslator extends BaseTranslator
    {
        public function transPlural($id, array $parameters = [], $locale = null, $domain = null)
        {
            // Custom pluralization logic
        }
    }
    

    Register as a service:

    # config/services.yaml
    services:
        App\Translation\CustomTranslator:
            decorates: 'dinecat_i18n.translator'
            arguments: ['@App\Translation\CustomTranslator.inner']
    
  2. Dynamic Translation Loading Load translations from a database or API:

    $translator->addResource(
        'yml',
        file_get_contents($dbTranslation->getContent()),
        $locale,
        $domain
    );
    
  3. Twig Extensions Add custom Twig functions for complex translations:

    $twig->addFunction(new \Twig\TwigFunction('trans_with_fallback', [$translator, 'trans'], ['is_safe' => ['html']]));
    
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.
codifyo/ts-generator-bundle
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