silex and twig localization

孤街醉人 提交于 2019-12-25 13:16:11

问题


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



来源:https://stackoverflow.com/questions/31502805/silex-and-twig-localization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!