树枝 "trans with" 不工作

Twig "trans with" not working

我在我的模板中使用了 twig trans 标签,我想像这样在其中传递变量:

{% trans with {
   '%link_start%': '<a href="http://www.google.nl/">',
   '%link_end%': '</a>'
} %}
    This %link_start%disclaimer%link_end% applies to all of our messages.
{% endtrans %}

但这给了我以下异常,它指向 {% trans with 行的树枝模板:

PHP Fatal error: Uncaught exception 'Twig_Error_Syntax' with message 'Unexpected token "punctuation" of value "{" ("end of statement block" expected).' in [twig-template:line]

即使我复制并粘贴 Symfony documentation 中的示例,我也会遇到同样的异常。所以我很茫然,我在这里做错了什么?

仅供参考:我使用的是启用了 i18n 扩展的 Twig 1.33(我没有使用 Symfony 框架)

Twig 不支持开箱即用的 trans with。它是 Symfony 翻译扩展的一部分。这就解释了为什么即使是官方的 Symfony 文档也不起作用——你没有使用 Symfony。

看到这个问题:https://github.com/twigphp/Twig-extensions/issues/74. There is a pull request支持trans with,但是还没有合并

您可能想在您的应用程序中使用 Symfony Translation Component。您可以在您的应用程序中使用 Symfony 组件,即使不使用完整的 Symfony(框架)堆栈。

我没试过,不过你可以试试用jhogervorst/Twi18n代替。

作为解决方法,您可以使用 filter tag with replace.

{% filter replace({'%foo%': 'blue', '%bar%': 'red'}) %}
  {% trans %}
    I like %foo% and %bar% messages.
  {% endtrans %}
{% endfilter %}