我正在尝试使用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扩展添加到twig环境中。如果我这样做,反函数中的文本就不会被翻译,因为我没有像我应该使用的那样使用过滤器。要使其工作,我需要使用如下所示的反式过滤器:{{ 'Some text'|trans }}。
是否有办法使翻译工作与{% trans 'Some text' %},而不是{{ 'Some text'|trans }}?例如,我可以在链中的某个地方添加一个自定义的反式函数吗?
备注:--我知道{% trans %}Some text{% endtrans %}可以工作,但是我的所有模板都已经使用了这个语法{% trans 'Some text' %},我想避免重写所有的东西。
发布于 2019-01-10 22:48:11
这个问题似乎来源于不兼容的twig和symfony的翻译本。但我不确定。
在我的例子中,我通过编写一个简单的脚本来将错误的语法替换为每个模板文件中正确的语法,从而长期解决了这个问题。
foreach (glob("your_template_path/*/*/*.twig") as $filename) {
$content = file_get_contents($filename);
$content = preg_replace_callback('/{% trans "[\s\S]+?" %}/',function($matches) {
$text = str_replace(['{% trans','%}','"'],'',$matches[0]);
return '{% trans %}'.trim($text).'{% endtrans %}';
},$content);
$content = preg_replace_callback('/{% trans \'[\s\S]+?\' %}/',function($matches) {
$text = str_replace(['{% trans','%}',"'"],'',$matches[0]);
return '{% trans %}'.trim($text).'{% endtrans %}';
},$content);
file_put_contents($filename,$content);
}也许这能帮上忙。
发布于 2022-03-10 17:22:05
尝尝这个
"{% trans %}Hello {% endtrans }!“
https://stackoverflow.com/questions/52349660
复制相似问题