如何在Symfony2中使用Gettext(.mo / .po)文件?

3

我想在 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 的帮助配置了默认的本地变量为法语(fr) http://symfony.com/doc/current/book/translation.html#the-locale-and-the-url

当我访问 app_dev.php/fr/hello/test 时,我的“Hello World”是英文的。我还需要配置其他什么吗?

已尝试此配置:在Symfony 2中配置翻译组件以使用gettext

2个回答

4

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

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

首先,在parameters.yml中添加default_locale参数:

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');


在Symfony 4中运作良好,谢谢!但是不必将加载器添加到services.yml文件中。 - Daviz

1

经过几天的研究,我终于找到了答案。虽然不是我一开始寻找的那个,但这是一个非常好的替代方案。

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

非常容易使用,我建议您使用“路由”来更改语言环境,类似于:

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

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接