Currently, I develop a website by using the PHP micro-framework Silex . Now I try to use " TranslationServiceProvider " to translate my website into different languages. To achieve this, I have set the " locale " parameter :
$app->register(new Silex\Provider\TranslationServiceProvider(), array(
'locale' => 'pt'
));
Then, in my controller, I call the function "setLocale", like this:
$app['translator']->setLocale('it');
Now, if I display, always in my controller, the result of the translation its works fine:
$app['translator']->trans("hello"); // return "Buongiorno"
$app['translator']->getLocale(); // return "it"
But, if I call the same function in my template Twig, translation does not work:
{{ app.translator.trans('hello') }} // return: "Olá"
{{ app.request.locale }} // return: "pt"
So, I don't understand: translation works fine in my controller but when I want access translations in Twig, nothing happens.
Do you have any idea about what's going on?
Finally, I've found a solution to resolve my problem. In my "app.php" file, I have added the following code :
$app->before(function () use ($app) {
if ($locale = $app['request']->get('lang') or $locale = $app['request']->getSession()->get('_locale')) {
$app['locale'] = $locale;
$app['request']->setLocale($locale);
}
});
Then, I've written a function in my controller to change language:
public function changeLanguageAction(Request $request, Application $app, $language)
{
$app['request']->getSession()->set('_locale', $language);
return $app->redirect($app["url_generator"]->generate('index'));
}
Now, when I call "changeLanguage" function, all the translations work fine.
I don't know if this solution is a good practice but it works...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.