@@ -827,6 +827,69 @@ checks translation resources for several locales:
827827 add the missing translation to the log file. For details,
828828 see :ref: `reference-framework-translator-logging `.
829829
830+ Switch Locale Programmatically
831+ ------------------------------
832+
833+ .. versionadded :: 6.1
834+
835+ The ``LocaleSwitcher `` was introduced in Symfony 6.1.
836+
837+ Sometimes you need to change the locale of the application dynamically
838+ just to run some code. Imagine a console command that renders Twig templates
839+ of emails in different languages. You need to change the locale only to
840+ render those templates.
841+
842+ The ``LocaleSwitcher `` class allows you to change at once the locale
843+ of:
844+
845+ * All the services that are tagged with ``kernel.locale_aware ``;
846+ * ``\Locale::setDefault() ``;
847+ * If a request is available, the ``_locale `` request attribute.
848+
849+ .. code-block :: php
850+
851+ use Symfony\Component\Translation\LocaleSwitcher;
852+
853+ class SomeClass
854+ {
855+ private LocaleSwitcher $localeSwitcher;
856+
857+ public function __construct(LocaleSwitcher $localeSwitcher)
858+ {
859+ $this->localeSwitcher = $localeSwitcher;
860+ }
861+
862+ public function someMethod()
863+ {
864+ // you can get the current application locale like this:
865+ $currentLocale = $this->localeSwitcher->getLocale();
866+
867+ // you can set the locale for the entire application like this:
868+ // (from now on, the application will use 'fr' (French) as the
869+ // locale; including the default locale used to translate Twig templates)
870+ $this->localeSwitcher->setLocale('fr');
871+
872+ // reset the current locale of your application to the configured default locale
873+ // in config/packages/translation.yaml, by option 'default_locale'
874+ $this->localeSwitcher->reset();
875+
876+ // you can also run some code with a certain locale, without
877+ // changing the locale for the rest of the application
878+ $this->localeSwitcher->runWithLocale('es', function() {
879+
880+ // e.g. render here some Twig templates using 'es' (Spanish) locale
881+
882+ });
883+
884+ // ...
885+ }
886+ }
887+
888+ .. note ::
889+
890+ The class :class: `Symfony\\ Component\\ Translation\\ LocaleSwitcher ` is
891+ autowired to the ``translation.locale_switcher `` service.
892+
830893Translating Database Content
831894----------------------------
832895
0 commit comments