简体   繁体   中英

Symfony translation with placeholder doesn't work

I'm trying to translate my app with Symfony translate (5.1.*). I use Symfony 5.1. Basic translation work fine but I have problem with variable in twig.

When I do {% trans with {'%name%': 'World'} from 'app' %}Hello %name%{% endtrans %}

It works fine and the result is Hello World as expected. But if I do

php bin/console translation:update --force en
php bin/console cache:clear

to generate the translation file, the result is Hello %name% .

If in the translation file, I delete this reference:

<trans-unit id="yhpYN0i" resname="Hello %name%">
    <source>Hello %name%</source>
    <target>Hello %name%</target>
</trans-unit>

the result is again Hello World .

Anybody has any idea why the translation file doesn't work when using a variable?

If you are using the ICU message format , the placeholders have to be {} . As the documentation states:

In the previous translation format, placeholders were often wrapped in % (eg %name%). This % character is no longer valid with the ICU MessageFormat syntax, so you must rename your parameters if you are upgrading from the previous format.

You'd have to change your translation file to:

<target>Hello {name}</target>

And remove % from your twig helper call

{% trans with {'name': 'World'} from 'app' %}Hello %name%{% endtrans %}

To keep using the old format if you don't need the pluralization rules provided by ICU you can rename the translation file to remove the +intl-icu suffix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM