You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If we want to render a template using a locale different from the one in the request, then there's no way to access this locale from within the template. Only solution is to inject it as a context variable:
It would be nice to be able to access the current locale with something like this:
<p>Locale: {{ app.locale }}!</p>
I know there's the app.request.locale approach, but this fails when using the LocaleSwitcher::runWithLocale() with a different locale that the request one.
Example
The AppVariable service could have a getLocale() function which retrieves the current locale being used from the LocaleSwitcher::getLocale() or the \Locale::getDefault() functions.
<p>Locale: {{ app.locale }}!</p>
The text was updated successfully, but these errors were encountered:
aprat84
changed the title
[Twig] Add current locale to AppVariable service
[TwigBridge] Add current locale to AppVariable service
Mar 30, 2023
…iable` (SVillette)
This PR was squashed before being merged into the 6.3 branch.
Discussion
----------
[TwigBridge][TwigBundle] Add current locale to `AppVariable`
| Q | A
| ------------- | ---
| Branch? | 6.3
| Bug fix? | no
| New feature? | yes
| Deprecations? | no
| Tickets | Fix#49870
| License | MIT
| Doc PR | symfony/symfony-docs#18190
As stated in #49870, they were no way to get the current locale without passing it through a variable when rendering a template within `LocaleSwitcher::runWithLocale()`.
```php
#[AsController]
final class HomeController
{
#[Route('/', name: 'app_home')]
public function __invoke(LocaleSwitcher $localeSwitcher, Environment $twig): Response
{
$localeSwitcher->setLocale('en');
return $localeSwitcher->runWithLocale('fr', function () use ($twig) {
return new Response($twig->render('index.html.twig'));
});
}
}
```
```twig
{{ app.locale }} // fr
```
A doc PR will be submitted if this change is accepted.
Commits
-------
2371216 [TwigBridge][TwigBundle] Add current locale to `AppVariable`
Description
If we want to render a template using a locale different from the one in the request, then there's no way to access this locale from within the template. Only solution is to inject it as a context variable:
It would be nice to be able to access the current locale with something like this:
I know there's the
app.request.locale
approach, but this fails when using theLocaleSwitcher::runWithLocale()
with a different locale that the request one.Example
The
AppVariable
service could have agetLocale()
function which retrieves the current locale being used from theLocaleSwitcher::getLocale()
or the\Locale::getDefault()
functions.The text was updated successfully, but these errors were encountered: