带树枝翻译的翻译器组件

时间:2018-09-15 23:18:39

标签: php symfony twig

我正在尝试使用Symfony转换器组件和.mo文件来翻译我的树枝模板。我以前使用过i18n扩展,但是想要一种更可靠的方法,因为在Windows上进行语言环境的翻译是一场噩梦。

这些类函数准备翻译和模板:

/**
 * Constructor.
 *
 * @param string $template_dir 
 * @param string $locale
 * @param string $locale_path
 */
public function __construct($template_dir, $locale, $locale_path)
{

    $loader = new Twig_Loader_Filesystem($template_dir);
    $this->parser = new TemplateNameParser();
    $this->template = new \Twig_Environment($loader);
    $this->translator = new Translator($locale);
    $this->translator->addLoader('mo', new \Symfony\Component\Translation\Loader\MoFileLoader());
    $this->translator->addResource('mo', $locale_path, $locale);
    $this->template->addExtension(new TranslationExtension($this->translator));

}
/**
 * Render template.
 */
public function render($name,$parameters=[]) {
    return $this->template->loadTemplate($name,$parameters)->render();
}

然后我有这个模板:

<h1>{% trans 'Hello World!' %}</h1>

会引发此错误:

  

未捕获的Twig_Error_Syntax:意外的令牌。树枝正在寻找   “ with”,“ from”或“ into”关键字。

我知道这是因为我没有将Twig_Extensions_Extension_I18n扩展名添加到树枝环境中。如果我这样做,则不会翻译trans函数中的文本,因为我没有按我的要求使用过滤器。为了使其正常工作,我需要像下面这样使用trans过滤器:{{ 'Some text'|trans }}

是否有一种方法可以使{% trans 'Some text' %}而不是{{ 'Some text'|trans }}进行翻译?例如,我可以在链中的某个位置添加自定义trans函数吗?

注意::我知道{% trans %}Some text{% endtrans %}可以工作,但是我所有的模板都已经使用了这种语法{% trans 'Some text' %},并且我想避免必须重写所有内容。

1 个答案:

答案 0 :(得分:0)

问题似乎源于不兼容的树枝和symfony翻译器版本。但是我不确定tbh。

就我而言,我通过编写一个简单的脚本以用每个模板文件中的正确语法替换不正确的语法来长期解决该问题。

TestBed.overrideProvider(QuestionManagementService,{useValue: new MockQuestionManagementService},);

也许可以帮助某人。

相关问题