CDO
CDO

Reputation: 131

How to use Gettext (.mo/.po) files with Symfony2?

I want to use Gettext for the translation of my website on Symfony2

In ../Resources/translations/ i have my translations files like that :

translations/en/LC_MESSAGES/en.mo
translations/en/LC_MESSAGES/en.po
translations/fr/LC_MESSAGES/fr.mo
translations/fr/LC_MESSAGES/fr.po
...

I already configured the default local variable with the help of Symfony2 cookbook to be french(fr) http://symfony.com/doc/current/book/translation.html#the-locale-and-the-url

When i go to app_dev.php/fr/hello/test, my Hello World is in english. There is something else i need to configure?

Already tried this configuration : Configure Translation component in Symfony 2 to use get text

Upvotes: 3

Views: 2912

Answers (2)

Francesco Borzi
Francesco Borzi

Reputation: 62004

Using Gettext (.mo/.po) files with Symfony is very simple and does not require any additional bundle.

The following is an example about how to use *.po files for translations.

First add the default_locale parameter in parameters.yml:

parameters:
    # ...
    default_locale: en_US
    # ...

Then enable the translator in config.yml:

framework:
    # ...
    translator:
            enabled: true
            fallbacks: ['%default_locale%']
            paths:
                - '%kernel.root_dir%/Resources/translations'
    # ...

And add the service to the services.yml file:

translation.loader.po:
    class: Symfony\Component\Translation\Loader\PoFileLoader
    tags:
        - { name: translation.loader, alias: po }

Place your mo/po translation files under app/Resources/translations using the following structure:

app/Resources/translations/messages.en.po

app/Resources/translations/messages.it.po

...

Now from your controllers you can call:

$this->get('translator')->trans('my.message.id');

Upvotes: 4

CDO
CDO

Reputation: 131

After few days of research, I finally found an answer. It's not the one that i was searching for, but it's a very good alternative.

I found this Awesome Bundle : https://github.com/LeaseWeb/LswGettextTranslationBundle

Very easy to put in place, i recommend you to use "routes" to change locales like that :

prefix:   /{_locale}/
    requirements:
        _locale: |fr|en|es|pt #All your locales "shortcuts"

Be sur to configure the Bundle to use locales shortcuts in Lsw/GettextTranslationBundle/Resources/config/config.yml like that :

parameters:
    gettext.locale_shortcuts:
        en: en_US
        fr: fr_FR
        pt: pt_PT
        es: es_ES

For all configurations, use the step by step bundle configurations (easy to use)

Upvotes: 1

Related Questions