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 Routing Bundle Laravel Package

benatespina/i18n-routing-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require benatespina/i18n-routing-bundle
    

    Ensure JMSI18nRoutingBundle is already installed (this bundle extends it).

  2. Enable the Bundle: Add to config/bundles.php:

    BenatEspina\I18nRoutingBundle\BenatEspinaI18nRoutingBundle::class => ['all' => true],
    
  3. Configure Locales: Extend jms_i18n_routing config in config/packages/jms_i18n_routing.yaml:

    jms_i18n_routing:
        default_locale: en
        locales: [en, es, fr]
        routing:
            locale_prefix: true
            prefix_default_locale: false
    
  4. First Use Case: Generate locale-aware routes in a controller:

    use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
    
    public function index(UrlGeneratorInterface $router)
    {
        return $this->render('home/index.html.twig', [
            'homepageUrl' => $router->generate('homepage', [], UrlGeneratorInterface::ABSOLUTE_URL),
            'esHomepageUrl' => $router->generate('homepage', ['_locale' => 'es'], UrlGeneratorInterface::ABSOLUTE_URL),
        ]);
    }
    

Implementation Patterns

Core Workflows

  1. Locale Prefix Routing:

    • Prefix routes with /{locale} (e.g., /es/contact).
    • Configure via locale_prefix: true in jms_i18n_routing.yaml.
    • Useful for SEO and clear URL structure.
  2. Dynamic Locale Switching:

    • Override locale per request via _locale route parameter:
      $router->generate('product_show', ['id' => 1, '_locale' => 'fr']);
      
    • Integrate with middleware to auto-detect locale (e.g., from Accept-Language header).
  3. Fallback Locales:

    • Define fallback chains in config:
      jms_i18n_routing:
          locales: [en, es, fr]
          fallback_locales: [en, es]
      
    • Fallback to en if es is unavailable.
  4. Route Annotations:

    • Use @Route with _locale parameter:
      /**
       * @Route("/product/{id}", name="product_show", requirements={"_locale": "en|es|fr"})
       */
      public function show(Product $product) { ... }
      

Integration Tips

  • Twig Integration: Use the path() and url() functions with _locale:

    <a href="{{ path('homepage', {'_locale': 'es'}) }}">Ir a Español</a>
    
  • APIs: For APIs, avoid locale prefixes and rely on _locale headers or parameters:

    # config/routes/api.yaml
    api_product:
        path: /api/product/{id}
        controller: App\Controller\ApiProductController::show
        methods: GET
        requirements:
            _locale: en|es|fr
    
  • Testing: Mock the RequestContext to test locale-specific routes:

    $context = $this->createMock(RequestContext);
    $context->expects($this->any())->method('getParameter')->with('locale')->willReturn('es');
    $router->setContext($context);
    

Gotchas and Tips

Common Pitfalls

  1. Locale Parameter Conflicts:

    • Avoid naming route parameters _locale if you also use it as a query parameter.
    • Fix: Use ?locale=es instead of _locale=es in URLs.
  2. Caching Issues:

    • Clear cache after changing locale configurations:
      php bin/console cache:clear
      
  3. Deprecated Features:

    • The bundle is outdated (last release 2017). Test thoroughly with Symfony 5/6.
    • Workaround: Override services if needed (e.g., router.request_context).
  4. Route Generation Edge Cases:

    • Ensure _locale is included in requirements for routes:
      requirements:
          _locale: en|es|fr
      
    • Error: No route found for "..." if locale is invalid.

Debugging Tips

  • Check Current Locale: Use a Twig extension or dump the RequestContext:

    {{ dump(app.request.attributes.get('_locale')) }}
    
  • Route Debugging: Enable debug toolbar and inspect the Router component for generated paths.

  • Logs: Enable verbose routing logs in config/packages/dev/monolog.yaml:

    handlers:
        routing:
            type: stream
            level: debug
            channels: ["routing"]
    

Extension Points

  1. Custom Locale Provider: Extend LocaleProvider to add logic (e.g., database-based locales):

    // src/Service/CustomLocaleProvider.php
    class CustomLocaleProvider implements LocaleProviderInterface
    {
        public function getLocales(): array
        {
            return ['en', 'es', 'custom_locale'];
        }
    }
    

    Register as a service and override the bundle’s locale_provider tag.

  2. Override Route Loader: Replace the default JMS\I18nRoutingBundle\Loader\RouterLoader with a custom implementation.

  3. Add Locale to Request: Use an event subscriber to attach locale to the Request object:

    // src/EventListener/LocaleListener.php
    class LocaleListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                KernelEvents::REQUEST => 'onKernelRequest',
            ];
        }
    
        public function onKernelRequest(GetResponseEvent $event)
        {
            $request = $event->getRequest();
            $request->attributes->set('_locale', 'es'); // Force locale
        }
    }
    

Configuration Quirks

  • Default Locale Handling: If prefix_default_locale: true, omit _locale for the default locale (e.g., /contact instead of /en/contact). Caveat: May cause confusion in multi-locale APIs.

  • Locale-Specific Assets: Use the asset() function with _locale for locale-specific JS/CSS:

    <link rel="stylesheet" href="{{ asset('css/styles_' ~ app.request.attributes.get('_locale') ~ '.css') }}">
    
  • Symfony 5+ Compatibility: The bundle lacks Symfony 5/6 support. Use symfony/flex recipes or manually patch the Router service if needed.

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui