I am trying to integrate the use of the Symfony Translate component into Slim 4 to create a multi-lingual application. I am facing a problem with setting the locale in the container and then retrieving it with the Twig View with the proper translation resource.
I have created a custom routing middleware that is supposed to capture the locale and store it in the container.
$path = $request->getUri()->getPath();
$params = $path === '/' ? [] : explode('/', substr($path, 1));
// check route for allowed locales
if (count($params) > 0 && in_array(strtolower($params[0]), $this->container->get('allowed_locales'))) {
$route->locale = strtolower(array_shift($params));
$this->container->set('locale', $route->locale);
}
I have created a definition in container to initialize the Twig View with Translation component:
'view' => function (ContainerInterface $container) {
return TwigFactory::createWith($container);
}
The TwigFactory:
class TwigFactory
{
public static function createWith(ContainerInterface $container): Twig
{
$locale = $container->get('locale');
$twig = Twig::create($twig_path, $twig_options);
$resourcePath = APPROOT . "/translations";
$translator = new Translator($locale, new MessageFormatter(new IdentityTranslator()));
$translator->setFallbackLocales(['en']);
$translator->addLoader('yaml', new YamlFileLoader());
if ( $locale !== 'en') {
$translator->addResource('yaml', "{$resourcePath}/messages.{$locale}.yaml", $locale, 'messages');
}
$translator->addResource('yaml', "{$resourcePath}/messages.en.yaml", 'en', 'messages');
$twig->addExtension(new TranslationExtension($translator));
if ($twig_options['debug']) {
$twig->addExtension(new DebugExtension());
}
return $twig;
}
}
In my controller, when the template is to be rendered:
$view = $this->container->get('view');
return $view->render($response, 'page.index.twig', $data);
The translation loaded is always English (en). It seems like the middleware is not setting the different locale in the container, or the definition is being processed by the container before the middleware has set the locale.
What am I doing wrong here?
PS: any input on how to use the TwigExtractor
in Symfony Translation component in a Slim 4 implementation will be appreciated as well.