-->

silex and twig localization

2019-09-12 08:31发布

问题:

I'm trying to implement translation in my web application with silex framework. So, i've come up with this

<?php

require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();
$app['debug'] = true;

$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/../views',
));

$app->register(new Silex\Provider\TranslationServiceProvider(array(
    'locale_fallbacks' => array('hr'),
)));


$app['translator'] = $app->share($app->extend('translator', function($translator) {

    $translator->addLoader('xlf', new \Symfony\Component\Translation\Loader\XliffFileLoader());

    $translator->addResource('xlf', __DIR__.'/../locales/hr.xlf', 'hr');
    $translator->addResource('xlf', __DIR__.'/../locales/en.xlf', 'en');
    $translator->addResource('xlf', __DIR__.'/../locales/sl.xlf', 'sl');

    return $translator;
}));


$app->get('/', function () use ($app) {

    $app['translator']->setLocale('hr');

    return $app['twig']->render('home.twig', array('d' => $app['translator']->getLocale()));

});


$app->get('/{_locale}/', function() use ($app) {
    $app['translator']->setLocale($app['request']->get('locale'));

    return $app['twig']->render('home.twig', array('d' => $app['translator']->getLocale()));
});



$app->run();

Basically, i'd like my homepage (mysite.com) default to hr locale but i can't get it to work. Translations are working properly but when i check for locale in my twig template i get 'en' (I need that check to output some extra text depending on locale). If i enter locale explicitly like mysite.com/hr or mysite.com/en twig registers locale as expected.

Also, I'm wondering if it's good practice having multilingual page with no specified locale on homepage.

回答1:

Try

$app['locale'] = 'hr';

Silex default locale is set to 'en'.

More info in silex translation documentation