[Solved] Buttons to change language on my template

Hello,

Using Slim + Twig, I’d like to add buttons to my template to change from French to English, or English to French, and stay on the same page (not going to the home).

For example, the documentation page of my website has the url “www.mywebsite/fr/doc” in french and “www.mywebsite/en/doc” in english.

For my routes, I wrote:

return function (App $app) use ($DEFAULT_LANG) {
  $app->group('/{lang:(?:en|fr)}', function(Group $group) {
    $group->get('/doc', DocAction::class)->setName('doc');
  }
}

I also have other routes with more params, for example www.mywebsite/fr/profiles/{profileId}/{code} and I need profileId and code to be set.

I’d like to add a button in my template:

<a href="url_for(CURRENT_PAGE, {CURRENT_PARAMS, 'lang': 'en'}) }}"><img src="en.png"/></a>

Is there a way to get and send to twig the used CURRENT_PAGE and the CURRENT_PARAMS ?

In my CURRENT_PARAMS, I allways have the “lang” and I’d like to overwrite it to “en”.

My DocAction controller is

class DocAction extends AbstractAction {

  const TEMPLATE = '/doc/doc.twig';

  public function __invoke(Request $request, Response $response, $args): Response {

    return $this->render($response, Self::TEMPLATE);
  }

}

I’ve found the following. Maybe not very smart but it works…

$routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute();
$routeName = $route->getName();
$routeArguments = $route->getArguments();
$usual->routeName = $routeName;
$usual->routeArguments = $routeArguments;

then

protected function render(Response $response, string $template, array $params = [], int $httpStatusCode = 200): Response {
  $routeInformation = [
    'routeName' => $this->usual->routeName,
    'routeArguments' => $this->usual->routeArguments,
  ];

  $params2 = array_merge($this->usual->flashData, $params, $routeInformation);

  return $this->responder->render($response, $template, $params2, $httpStatusCode);
}

then in my template

<a href="{{ url_for(routeName, routeArguments | merge({'lang': 'fr'})) }}" class="flag">🇫🇷</a>
<a href="{{ url_for(routeName, routeArguments | merge({'lang': 'en'})) }}" class="flag">🇬🇧</a>```