Skip to content

Commit ba42e97

Browse files
committed
[Translation] document LocaleSwitcher
1 parent ceaadad commit ba42e97

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

translation.rst

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -827,6 +827,58 @@ 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`` 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+
830882
Translating Database Content
831883
----------------------------
832884

0 commit comments

Comments
 (0)