@@ -827,6 +827,58 @@ checks translation resources for several locales:
827
827
add the missing translation to the log file. For details,
828
828
see :ref: `reference-framework-translator-logging `.
829
829
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 `` object/service allows you to change at once the locale
843
+ of:
844
+
845
+ 1. All the services that are tagged with ``kernel.locale_aware ``.
846
+ 2. ``\Locale::setDefault() ``.
847
+ 3. If a request is available, the ``_locale `` request attribute.
848
+
849
+ The ``LocaleSwitcher `` service is autowireable and can be injected into other
850
+ services::
851
+
852
+ use Symfony\Component\Translation\LocaleSwitcher;
853
+
854
+ class SomeClass
855
+ {
856
+ public function __construct(
857
+ private LocaleSwitcher $localeSwitcher,
858
+ ) {}
859
+
860
+ public function someMethod()
861
+ {
862
+ // you can get the current application locale like this:
863
+ $currentLocale = $this->localeSwitcher->getLocale();
864
+
865
+ // you can set the locale for the entire application like this:
866
+ // (from now on, the application will use 'fr' (French) as the
867
+ // locale; including the default locale used to translate Twig templates)
868
+ $this->localeSwitcher->setLocale('fr');
869
+
870
+ // you can also run some code with a certain locale, without
871
+ // changing the locale for the rest of the application
872
+ $this->localeSwitcher->runWithLocale('es', function() {
873
+
874
+ // e.g. render here some Twig templates using 'es' (Spanish) locale
875
+
876
+ });
877
+
878
+ // ...
879
+ }
880
+ }
881
+
830
882
Translating Database Content
831
883
----------------------------
832
884
0 commit comments