frankdejonge / symfony-i18n-routing
Internationalised routing for Symfony 4
Installs: 2 776
Dependents: 0
Suggesters: 0
Security: 0
Stars: 17
Watchers: 1
Forks: 2
Open Issues: 0
Requires
- php: ^7.1.3
- symfony/config: ^4.0
- symfony/routing: ^4.0
Requires (Dev)
- doctrine/annotations: ^1.6
- matthiasnoback/symfony-dependency-injection-test: ^2.3
- nyholm/symfony-bundle-test: ^1.3
- phpunit/phpunit: ^6.0
- symfony/dependency-injection: ^4.0
- symfony/http-kernel: ^4.0
- symfony/yaml: ^4.0
README
This bundle provides i18n routing for Symfony 4.
Purpose
This bundle provides a method of internationalization of route definitions. This means you can define a path per locale and still have them route to the same controller action.
Installation
composer req frankdejonge/symfony-i18n-routing
Register the bundle in bundles.php
<?php return [ FrankDeJonge\SymfonyI18nRouting\I18nRoutingBundle::class => ['all' => true], // ... ];
Note that if you want to use the annotations you'll need to ensure this bundle is loaded BEFORE the FrameworkBundle.
Configuration
frankdejonge_i18n_routing: default_locale: en use_annotations: false # set to true to enable annotation loading
Yaml usage
From your main config/routes.yml
import your localized routes:
i18n_routes: resource: ./i18n_routes/routes.yml type: i18n_routes
Now you can define i18n routes in config/i18n_routes/routes.yml
:
contact: controller: ContactController::formAction locales: en: /send-us-an-email nl: /stuur-ons-een-email
This is effectively the same as defining:
contact.en: controller: ContactController::formAction path: /send-us-an-email defaults: _locale: en contact.nl: controller: ContactController::formAction path: /stuur-ons-een-email defaults: _locale: nl
As you can see this saves you a bit of typing and prevents you from having to keep 2 definitions in sync (less error prone).
Annotation usage
The annotation loader supports both normal route annotations and
localized ones. The @I18nROute
and @Route
annotations can be
be mixed at will.
<?php use FrankDeJonge\SymfonyI18nRouting\Routing\Annotation\I18nRoute; class ContactController { /** * @I18nRoute({"en": "/send-us-an-email", "nl": "/stuur-ons-een-email"}, name="contact") */ public function formAction() { } } /** * @Route("/prefix") */ class PrefixedContactController { /** * @I18nRoute({"en": "/send-us-an-email", "nl": "/stuur-ons-een-email"}, name="prefix_contact") */ public function formAction() { } }
Generating routes
Generating routes can be done using the specified route name.
<?php /** @var UrlGeneratorInterface $urlGenerator */ $urlWithCurrentLocale = $urlGenerator->generate('contact'); $urlWithSpecifiedLocale = $urlGenerator->generate('contact', ['_locale' => 'nl']);