Fork me on GitHub

Localization

The TranslationServiceProvider provides a service for translating your application into different languages.

This provider installs services: translator, translator.loader, translator.message_selector.

Silex use Symfony2 Translation component. Details can be see here.

Configuration

The provider configuration is defined in app/Resources/Config/config.yml file.

An example is shown below:

...
translation:
        class: Silex\Provider\TranslationServiceProvider
        parameters:
            locale_fallbacks: [en, ru]
            locale: %locale% 
...

Extend the functionality of the service is defined in the action _extendServices of class Bootstrap app/Bootstrap.php.

An example is shown below:

...
//Extend translator
if (isset($app['translator']) AND $app['translator'] instanceof \Silex\Translator) {
    $app['translator'] = $app->share(
            $app->extend(
                    'translator', function (\Silex\Translator $translator, $app) {
                $translator->addLoader('yml', new Loader\YamlFileLoader());
                $translator->addResource('yml', BASEPATH . '/app/Resources/translations/messages.en.yml', 'en', 'messages');
                $translator->addResource('yml', BASEPATH . '/app/Resources/translations/messages.ru.yml', 'ru', 'messages');
                $translator->addResource('yml', BASEPATH . '/app/Resources/translations/Validators.en.yml', 'en', 'validators');
                $translator->addResource('yml', BASEPATH . '/app/Resources/translations/Validators.ru.yml', 'ru', 'validators');

                if ($app['session']->has('_locale')) {
                    $locale = $app['session']->get('_locale');
                    $translator->setLocale($locale);
                }
                return $translator;
            }
            )
    );
}
...

Here are specified some resource files using a translator. In our case it yml files, which are located in the directory app/Resources/translations/.

You can set the default language of localization in the file parameters.yml in parameter locale.

Using

Additional localization functions are specified in trait app/Controllers/Helper/TranslateTrait.

Service Translation can be used as:

$this->addFlash('info_message', $this->trans('added_new_message', array('' => $ormPost->getTitle())));

Service Translation in the template can be used as:

{ { 'edit'|trans|capitalize } }