symfony & translation : How to translate standard expressions & forms?

217 Views Asked by At

New to Symfony I created a login form (make:auth) and installed the translator. I added in my form template login.html.twig

    {% block body %}
    <h1>{% trans %}Hello{% endtrans %}</h1>
    <form method="post">
...

and defined in translations directory a messages.fr.yml, containing Hello : Bonjour.

That works and when I display my form, hello is well translated to Bonjour

But, all the other labels are not translated (username, password, etc)

which seems to be logical as the entries do not have the {% trans %} {% endtrans %} commands

    <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="inputUsername" class="sr-only">Username</label>

question 1 : is there a way to automatically translate all these labels?

question 2 : is there existing translation files containing all the standard used messages / labels?

Thank you for your help

2

There are 2 best solutions below

0
On

The default for form labels is to use a "humanized" version. And that one then may be translated in the messages translation domain.

You can change that by either setting the label on the form (element) directly, either in the builder

->add('fieldName', TextType::class, [
      'label' => 'fieldName_translation_key',
])

or in the template:

{{ form_row(form.fieldname, {label: 'fieldname_translation_key'}) }}

{# this also works with form_widget/form_label, depending on the form element #}

If you want to use keyword translations for fields, you can set the label_format on the form itself (in the configure method, as an option) or on all its elements manually (with the placeholders described).

I personally prefer the label_format method because I rarely render the form "manually".

You can also set the translation_domain parameter to change the used translation domain (messages) to something else.

2
On

to manage the translation in twig there is the appropriate trans function (example):

<label for="inputUsername" class="sr-only">{{'username' | trans}}</label>

and in your messages.fr.yml add:

username: "Nom d'utilisateur"