Search code examples
phpsymfonyroutestwigsymfony4

Creating URLs containing the locale in Symfony 4


I am creating a Symfony 4 web app that supports multiple languages. The routing is done, so I can have /en/suchpage or /de/suchpage. I am now looking for a way to link to "suchpage" using the right locale.

Routing looks as follows:

suchpage:
    path: /{_locale}/suchpage/
    controller: App\Controller\SimplePageController::such
    requirements:
        maw: '%app.locales%'
    defaults:
        _locale: '%locale%'

I am using Twig, and it is from Twig templates that I need to be able to link to the right version of a page. This "works":

{{ path('suchpage', {'_locale': app.request.locale}) }}

It has two issues though:

  1. I do not want to be repeating this all over the place. Something like {{ page('suchpage') }} would be much better. Does a function like this exist? Can path() be made to behave like this?

  2. This fails if the locale was not specified in the request, as can happen, since it is not required on all pages (since some have a default).


Solution

  • There is a maintened bundle, JMSI18nRoutingBundle, to achieve what you need.

    composer require jms/i18n-routing-bundle

    Some usefull links about this bundle :

    Packagist : https://packagist.org/packages/jms/i18n-routing-bundle

    GitHub : https://github.com/schmittjoh/JMSI18nRoutingBundle