I am using Twig, twig-bridge, symfony/form and symfony/translator v4. Not Symfony framework. I am confused about translator. In {root}/translations/messages.fr.php I wrote:
setlocale(LC_ALL, 'fr_FR');
$translator = new Translator('fr');
$translated = $translator->trans('Symfony is great');
var_dump($translated); // Not translated!
and in Twig template I wrote:
<h1>{% trans %}Symfony is great{% endtrans %}</h1>
But this is not translated. I still get the english version. What mistake I did? Should I move {root}/translations/messages.fr.php to somewhere else as this is standalone and not symfony framework?
The Symfony framework wires up the translator to look for translations in the {root}/translations directory. When you don’t use the framework you have to do this yourself.
This works:
<?php
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\Loader\PhpFileLoader;
require __DIR__ . '/vendor/autoload.php';
$translator = new Translator('fr');
$translator->addLoader('php', new PhpFileLoader());
$translator->addResource(
'php',
__DIR__.'/translations/messages.fr.php',
'fr'
);
$translated = $translator->trans('Symfony is great');
var_dump($translated); // string(14) "J'aime Symfony"