Search code examples
symfonypathtwigtranslationlocale

Symfony Twig - get default _locale in twig


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 :)


Solution

  • 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')
    {
        ...
    }