9

When I was doing plain PHP, I was simply doing this:

printf(_("Hello %s !"), $name);

Now with Twig, I must use the trans tag. So I've copy/paste the documentation example, and here's my full template:

{% extends 'MyAppBundle::layout.html.twig' %}

{% block content %}
    <h1>
        {% trans %}
            Hello {{ name }}!
        {% endtrans %}
    </h1>
{% endblock %}

Why Symfony return the following exeption ?

A message must be a simple text in "MyAppBundle::home.html.twig"

500 Internal Server Error - Twig_Error_Syntax

j0k
  • 22,600
  • 28
  • 79
  • 90
FMaz008
  • 11,161
  • 19
  • 68
  • 100

3 Answers3

21

One missing bit with the previous answer is the "with" portion that is needed to do the replacement of the variable part of the message.

{% trans with {'%name%':name} %}Hello %name%!{% endtrans %}
roverwolf
  • 451
  • 3
  • 4
11

The precise syntax for translations is a little different in Symfony2 than it is in standalone Twig. You'll want to check out the Symfony2 documentation for translations in twig templates, found here. The correct syntax would look something like this:

{% trans %}Hello %name%!{% endtrans %}
Problematic
  • 17,567
  • 10
  • 73
  • 85
0

I have a similar issue: to pass my translation path to trans filter, I need to concatenate a string and a variable, then transform into lowercase.

Here {% trans %} and {% endtrans %} are not used, but trans filter instead:

<span>{{ ('statuses.' ~ status | lower) | trans }}</span>

Assuming in the translation there is:

- status:
  - failed: The task has failed

and in the template you pass the variable name with value FAILED.

Thykof
  • 895
  • 7
  • 9