Php Symfony2中的高级翻译定制
我有一个Php Symfony2中的高级翻译定制,php,symfony,translation,Php,Symfony,Translation,我有一个Symfony2项目,我正在使用Translation组件翻译文本。我在yml文件中有这样的所有翻译 translation-identifier: Translated text here 从Twig 'translation-identifier'|trans({}, 'domain') 问题是,在某些情况下,我希望有两个不同的文本用于相同的翻译(而不是复数)。以下是我希望它的工作方式: 在yml文件中定义两个需要不同文本的翻译文本。每个都有自己独特的后缀 translation
Symfony2
项目,我正在使用Translation
组件翻译文本。我在yml
文件中有这样的所有翻译
translation-identifier: Translated text here
从Twig
'translation-identifier'|trans({}, 'domain')
问题是,在某些情况下,我希望有两个不同的文本用于相同的翻译(而不是复数)。以下是我希望它的工作方式:
yml
文件中定义两个需要不同文本的翻译文本。每个都有自己独特的后缀
translation-identifier-suffix1
translation-identifier-suffix2
public function getSuffix() {
return rand(0, 10) < 5 ? '-suffix1' : '-suffix2';
}
公共函数getSuffix(){
返回rand(0,10)<5?'-suffix1':'-suffix2';
}
抱歉,转换器组件不支持它 但是,如果您想要相同的行为,可以通过重写translator服务来实现 1) 覆盖服务
# app/config/config.yml
parameters:
translator.class: Acme\HelloBundle\Translation\Translator
首先,您可以通过在app/config/config.yml
中进行设置,将保存服务类名的参数设置为您自己的类。
供参考:
2) 扩展提供的转换器类symfony框架包
。
供参考:
3) 覆盖转换器组件提供的trans
功能。
希望这有帮助 这是一个扩展的translator类,以防任何人需要它
<?php
namespace Acme\HelloBundle\Translation;
use Symfony\Bundle\FrameworkBundle\Translation\Translator as BaseTranslator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\DependencyInjection\ContainerInterface;
class Translator extends BaseTranslator {
const SUFFIX_1 = '_suffix1';
const SUFFIX_2 = '_suffix2';
private $suffix;
public function __construct(ContainerInterface $container, MessageSelector $selector, $loaderIds = array(), array $options = array()) {
parent::__construct($container, $selector, $loaderIds, $options);
$this->suffix = $this->getSuffix($container);
}
public function trans($id, array $parameters = array(), $domain = 'messages', $locale = null) {
if ($locale === null)
$locale = $this->getLocale();
if (!isset($this->catalogues[$locale]))
$this->loadCatalogue($locale);
if($this->suffix !== null && $this->catalogues[$locale]->has((string) ($id . $this->suffix), $domain))
$id .= $this->suffix;
return strtr($this->catalogues[$locale]->get((string) $id, $domain), $parameters);
}
private function getSuffix($container) {
return rand(0, 10) < 5 ? self::SUFFIX_1 : self::SUFFIX_2;
}
}
?>
从Symfony 3开始,Venu的答案不再完全有效,因为不再使用translator.class
参数
要加载自定义转换器类,现在需要创建一个编译器过程
作为替代方案,您还可以装饰现有的转换器:这不再适用于Symfony 3。另一个解决方案请看下面。