@@ -299,33 +299,37 @@ Translatable Objects
299
299
300
300
Translatable objects were introduced in Symfony 5.2.
301
301
302
- Sometimes you may want to create a message, but at the time of creation aren't
303
- sure how it would be translated. For example, it could be translated multiple
304
- times if intended to be displayed to multiple users.
302
+ Sometimes translating contents in templates is cumbersome because you need the
303
+ original message, the translation parameters and the translation domain for
304
+ each content. Making the translation in the controller or services simplifies
305
+ your templates, but requires injecting the translator service in different
306
+ parts of your application and mocking it in your tests.
305
307
306
- Using translatable objects also allows preparing translations without having a
307
- dependency on an entrypoint (such as a router) where the context for performing
308
- the translation is provided. For example, entities could prepare translatable
309
- strings (such as labels) without the need for a translator.
308
+ Instead of translating a string at the time of creation, you can use a
309
+ "translatable object", which is an instance of the
310
+ :class: ` Symfony \\ Component \\ Translation \\ Translatable ` class. This object stores
311
+ all the information needed to fully translate its contents when needed::
310
312
311
- Instead of translating a string at the time of creation, a ``Translatable ``
312
- object can be created that can then be translated when used. Later this message
313
- can be translated with a translator in either PHP or in Twig.
314
-
315
- PHP::
313
+ use Symfony\Component\Translation\Translatable;
316
314
315
+ // the first argument is required and it's the original message
317
316
$message = new Translatable('Symfony is great!');
318
- $message = t('Symfony is great!');
319
-
320
- Translatable::trans($translator, $message );
317
+ // the optional second argument defines the translation parameters and
318
+ // the optional third argument is the translation domain
319
+ $status = new Translatable('order.status', ['order' => $order], 'store' );
321
320
322
- Twig:
321
+ Templates are now much simpler because you can pass translatable objects to the
322
+ ``trans `` filter:
323
323
324
324
.. code-block :: html+twig
325
325
326
- {% set message = t('Symfony is great!') %}
327
-
328
326
<h1>{{ message|trans }}</h1>
327
+ <p>{{ status|trans }}</p>
328
+
329
+ .. tip ::
330
+
331
+ There's also a :ref: `function called t() <reference-twig-function-t >`,
332
+ available both in Twig and PHP, as a shortcut to create translatable objects.
329
333
330
334
.. _translation-in-templates :
331
335
0 commit comments