Mario Legenda
Mario Legenda

Reputation: 759

Symfony2 creating routes based on language locale

I'm implementing translator for a multilingual site. It all works fine but when the user tries to change the language, the language stays the same.

This is the route...

index:
    path:  /{_locale}
    defaults: { _controller: HotelIndexBundle:Index:index , _locale:hr}
    requirements:
        _locale: hr|en

In a twig template I have to links that go to this path with...

path('index');

To lets say that I'm in my index page www.example.com (it defaults to 'hr'). The user then changes to www.example.com/en. It works. But when it tries to get back to hr with path('index'), the page reverts to same www.example.com/en.

There is also a problem with additional url parameters like www.example.com/en/contact. How to change it to www.example.com/hr/contact AND stay on the /contact page?

Upvotes: 0

Views: 309

Answers (2)

Chorochrondochor
Chorochrondochor

Reputation: 100

To lets say that I'm in my index page www.example.com (it defaults to 'hr'). The user then changes to www.example.com/en. It works. But when it tries to get back to hr with path('index'), the page reverts to same www.example.com/en.

You should have the following configuration in your config.yml file:

config.yml

framework:
    translator:      { fallback: "%locale%" }
    default_locale:  "%locale%"

The locale parameter should be defined in parameters.yml file:

parameters.yml

parameters:
    locale: hr

There is also a problem with additional url parameters like www.example.com/en/contact. How to change it to www.example.com/hr/contact AND stay on the /contact page?

It can be done like this:

{% set requestParams = app.request.attributes.get('_route_params') %}
{% set requestRoute = app.request.attributes.get('_route') %}

<a href="{{ path(requestRoute, requestParams|merge({'_locale' : 'en'})) }}">en</a>
<a href="{{ path(requestRoute, requestParams|merge({'_locale' : 'hr'})) }}">hr</a>

Upvotes: 2

Hubert Perron
Hubert Perron

Reputation: 3022

Take a look at the JMSi18nRoutingBundle. It does exactly what you want.

Upvotes: 2

Related Questions