1
votes

I'm adding a language switcher on my website.

my parameters are like this :

avc_coming_soon:
resource: "@AVCComingSoonBundle/Controller/"
type:     annotation
prefix:   /{_locale}
defaults:
    _locale: en
requirements:
    _locale: |fr

en is set by default

In my twig, I did that:

<div class="languages">
        <ul class="lang-menu">
            <li class="en"><a href="{{ path(app.request.get('_route'), {'_locale': 'en' })  }}"><img src="{{ asset('images/flag_en.gif') }}" alt="EN"></a></li>
            <li class="fr"><a href="{{ path(app.request.get('_route'), {'_locale': 'fr'})  }}"><img src="{{ asset('images/flag_fr.gif') }}" alt="FR"></a></li>
        </ul>
    </div>

But when I click on 'English', my path become www.mysite.com/en or the good route is www.mysite.com/ (without the /en) because in parameters, I have this :

defaults:
    _locale: en

How to get the default _locale in twig ?

{{ path(app.request.get('_route'), {'_locale': <<<default>>> })  }}

thank you :)

3

3 Answers

2
votes

You need to use app.request.attributes:

{{ path(app.request.get('_route'), {'_locale': app.request.attributes.get('_locale') })  }}

If you have configuration in controller you need to set default value in function parameter:

/**
 * @Route("/", name="coming_soon", options={"expose"=true}, requirements={"_locale" = "fr|en"})
 */
public function indexAction($_locale = 'en')
{
    ...
}
0
votes

I use this bundle: https://github.com/schmittjoh/JMSI18nRoutingBundle

Thanks to the bundle I never have to mess with locales..

You can configure the bundle to prefix everything except the default locale (which is what you wan't, reading the comments to the other answer).

And for the language switcher you simply set the _locale on any given route.

0
votes
app.request.session.get('_locale')