Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2+Twig, variable in translation return "A message must be a simple text"

Tags:

php

twig

symfony

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

like image 577
FMaz008 Avatar asked Oct 18 '11 17:10

FMaz008


2 Answers

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 %}
like image 180
roverwolf Avatar answered Nov 05 '22 10:11

roverwolf


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 %}
like image 42
Derek Stobbe Avatar answered Nov 05 '22 09:11

Derek Stobbe