symfony 搭建多语言
sanlanlan 2020-2-18 标签: symfony 浏览:2864 评论:0
以下是基于symfony3 配置使用的。
1.在 # app/config/config.yml 开启
locale: en //默认英文,可以自己修改
framework:
translator: { fallbacks: ["%locale%"] }
2.翻译文件一般放在,bundle 下的Resources/translations/
比如,可以在ApiBundle 下建一个 Resources/translations/ 目录(ApiBundle/Resources/translations),存放翻译文件。
文件命名:messages.fr_FR.yml,messages.zh_CN.yml
翻译文件命名规则:
French/France,locale就是fr_FR
en_GB
zh_CN
3.翻译文件写法:
symfony.token: 'write your token'
access.token: 'access %token%' //token 是变量
$token = $this->translator->trans('symfony.token');
5.在controller 直接调用的话,直接使用
$this->get('translator')->trans('access.token'), [['%token%'=>xxx])
6.在前端模板中使用:
{{ 'mail.welcome.letter.title'|trans }}
7.要设置用户的locale,你可能希望创建一个自定义的事件监听,以便它在系统的其他部分(比如translator)需要它之前就被设置好://http://symfony.com/doc/current/translation/locale.html
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
// some logic to determine the $locale
$request->setLocale($locale);
}
8.执行 console 命令 更新语言包
php bin/console translation:update --help //可以看到具体命令
比如更新英文包,可以执行:php bin/console translation:update en AppBundle --force
这样简单就搭建起来了。
具体详细信息,详见官网。
发表评论: