Translations
| Trans strings | |
| Set the locale | |
| Translation files | |
| Plural forms |
Trans strings
The translator turns a message id such as hello into the text of the current language. Call trans with the id wherever user facing output is produced.
Keep ids short and readable so templates and controllers share the same vocabulary. Add the default language text first, then translate it step by step.
namespace App\Controller; use Symfony\Contracts\Translation\TranslatorInterface; class HomeController { public function index(TranslatorInterface $translator): string { return $translator->trans("hello"); } }
Set the locale
The locale selects which language the translator uses for the current request. Common sources are the URL prefix, the user profile, or an explicit switch link.
Set the locale on the request early so all later translator calls pick it up. Store the choice in the session or profile to keep it stable across pages.
namespace App\Controller; use Symfony\Component\HttpFoundation\Request; class LocaleController { public function change(Request $request): void { $request->setLocale("fr"); } }
Translation files
Translation files map message ids to texts per language inside the translations folder. One file per language keeps reviews simple and avoids merge conflicts.
Name files with the domain and locale pattern so Symfony loads them automatically. Rebuild the cache after edits when the new text does not appear.
translations/messages.en.yaml translations/messages.fr.yaml
Plural forms
Plural messages change with the count, for example one item versus many items. Pass the count as a named parameter so the translator can select the correct form.
Use the count placeholder in code and define singular and plural variants in the translation file. Test with zero, one, and several values because rules differ by language.
namespace App\Controller; use Symfony\Contracts\Translation\TranslatorInterface; class CartController { public function count(TranslatorInterface $translator, int $total): string { return $translator->trans("items.count", ["%count%" => $total]); } }
Next: Dotenv and env
Article author: Arthur Isaev