如何将Gettext(.mo/.po)文件与Symfony2一起使用


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

我想在Symfony2 上使用Gettext翻译我的网站

../Resources/translations/中,我有这样的翻译文件:

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

我已经在Symfony2 cookbook的帮助下将默认本地变量配置为french(fr)http://symfony.com/doc/current/book/translation.html#the-区域设置和url

当我去app_dev.php/fr/hello/test的时候,我的Hello World是英文的。还有什么需要我配置的吗?

已经尝试过这种配置:在Symfony 2中配置翻译组件以使用get-text

在Symfony中使用Gettext(.mo/.po)文件非常简单,不需要任何额外的捆绑包。

以下是关于如何使用*.po文件进行翻译的示例。

首先在参数中添加default_locale参数。yml:

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

然后在config.yml:中启用翻译器

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

并将服务添加到services.yml文件:

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

使用以下结构将您的mo/po翻译文件放在app/Resources/translations下:

app/Resources/translations/messages.en.po

app/Resources/translations/messages.it.po

...

现在,从您的控制器,您可以调用:

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

经过几天的研究,我终于找到了答案。这不是我一直在寻找的,但它是一个很好的选择。

我发现这个很棒的捆绑包:https://github.com/LeaseWeb/LswGettextTranslationBundle

很容易设置,我建议你使用"路线"来更改这样的地区:

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

请将Bundle配置为使用Lsw/GettextTranslationBundle/Resources/config/config.yml中的语言环境快捷方式,如下所示:

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

对于所有配置,使用逐步捆绑配置(易于使用)