Wessel van der Linden
Wessel van der Linden

Reputation: 2622

Twig "trans with" not working

I'm using the twig trans tag in my templates, and I want to pass variables in it like so:

{% 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 %}

But this gives me the following exception which points to the twig template at the {% trans with line:

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

Even when I copy & paste the examples from the Symfony documentation I get the same exception. So I'm at a loss, what am I doing wrong here?

FYI: I'm using Twig 1.33 with the i18n extension enabled (and I'm not using the Symfony framework)

Upvotes: 4

Views: 1872

Answers (2)

Arnold Daniels
Arnold Daniels

Reputation: 16573

As a workaround you can use the filter tag with replace.

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

Upvotes: 0

Stephan Vierkant
Stephan Vierkant

Reputation: 10144

Twig doesn't support trans with out of the box. It is part of the Symfony translation extension. That explains why even the official Symfony documentation doesn't work - you are not using Symfony.

See this issue: https://github.com/twigphp/Twig-extensions/issues/74. There is a pull request to support trans with, but it hasn't been merged.

You might want to use the Symfony Translation Component in your application. You can use Symfony Components in your application, even without using the full Symfony (Framework) stack.

I haven't tried it, but you can try to use jhogervorst/Twi18n instead.

Upvotes: 2

Related Questions