How to translate with symfony translator?

I am using Twig, twig-bridge, symfony/form and symfony/translator v4. Not Symfony framework. I am confused about translator. In {root}/translations/ I wrote:

// translations/
return [
    'Symfony is great' => "J'aime Symfony",

In main script in {root} 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/ 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:


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());

$translated = $translator->trans('Symfony is great');
var_dump($translated); // string(14) "J'aime Symfony"

For more info, see

1 Like

The confirmation page after submitting the form. Should be a separated template file? Or better to use if clause in the same form template?

I would go for a separate template as that’s simpler, but that’s personal preference really.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.