'How to use gettext with Twig templates in Slim Framework?
I'm working with Slim 4 Framework with a Twig engine for templates.
Some time ago, Twig had an extension with {% trans %} tokens and |trans filter directly linked to gettext function.
Now things seems to be more complicated, Twig is linked to a Symfony Translator... do you know how can I link Twig to gettext?
I tried to create a custom filter, and it works, but I don't know how to create a tokenparser just to call gettext() function.
Solution 1:[1]
The "official" way would be to use the Twig-Bridge component that provides a Twig 3 TranslationExtension to translate messages with the trans
filter. For this, you have to install the Symfony translator component.
The TranslationExtension can be configured with a custom Translator that must implement the TranslatorInterface. The Symfony Translator is able to use mo files as source. So you don't have to use the gettext extension anymore.
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\Formatter\MessageFormatter;
use Symfony\Component\Translation\IdentityTranslator;
use Symfony\Component\Translation\Loader\MoFileLoader;
use Slim\Views\Twig;
// ...
$twig = Twig::create($paths, $options);
$translator = new Translator(
'en_US',
new MessageFormatter(new IdentityTranslator())
);
$translator->addLoader('mo', new MoFileLoader());
$twig->addExtension(new TranslationExtension($translator));
If you still want to use the gettext function, you could also try to create a custom Twig function:
https://symfony.com/doc/current/templating/twig_extension.html
use Twig\TwigFunction;
$environment = $twig->getEnvironment();
$environment->addFunction(new TwigFunction('__', function ($message) {
return __($message);
}));
Usage
{{ __('Hello world') }}
The downside of the second approach is that you need a custom text parser.
Solution 2:[2]
I have solved adding this dependency to composer:
twig/extensions
And this extension to Twig config:
$twig = Twig::create($twigSettings['path'], $twigSettings['settings']);
$twig->addExtension(new I18nExtension());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | odan |
| Solution 2 | Tobia |
