I am using Silex and Twig for a website and I want to allow the user to change the langage of the site.
Right now, it works if I change the loca
I finally find a solution to do what I want, using pmaxs/silex-locale (https://github.com/pmaxs/silex-locale).
As I said in my question, I already used it for my translation but I didn't used the "Url generation" as I should...So here is a recap of how to use it (read the documentation if you use Silex v1.x):
1/ Loading Provider
$app->register(new \Pmaxs\Silex\Locale\Provider\LocaleServiceProvider(), [
'locale.locales' => ['en', 'fr'], //I want to translate my site in English and French
'locale.default_locale' => 'en', // By default, the locale is "en"
'locale.resolve_by_host' => false,
'locale.exclude_routes' => ['^_']
]);
$app->register(new Silex\Provider\LocaleServiceProvider());
2/ Usage
Here is my home route controller :
// this page is accessible by urls '/', '/fr/' or '/en/'
$app->match('/', function (Request $request) use ($app) {
// my code
return $app['twig']->render('home.html.twig');
})->bind('home');
As you can see, I have no {_locale} variable in my routing, but still can use it to change the langage of my page.
3/ Url generator
Now, here is how I change my langage :
{% set locale_list = ["en", "fr"] %} // the list of all langage in my website
{% set current_locale = global.request.getLocale() %} // the current langage of my page
-
// I display the current langage
{{ current_locale|upper }}
{% for locale in locale_list %}
{% if locale != current_locale %}
// I create one link to change the langage according to all the langage I want, minus the current langage
{{ locale|upper }}
{% endif %}
{% endfor %}
I'm using the "Url Generator", it works like this : locale_generate('es', $name, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH) (more details in the documentation).
This way, when I come in my website I'm in english (my default locale) with my "clean Url" /. Then by clicking on FR my url become /fr/ and my content is translate in French with a new selection menu (current-langue = FR and I can select "EN").