Question

I have an array filled with all countries name and I want to translate this names but I don't know how

In my controller I did:

$countries = array("Afghanistan", "Albania", "Algeria", "Angola", ....);

return $this->render('xBundle:x:xs.html.twig', array('countries' => json_encode($countries))

And in my template I have:

List : {{countries}}
Was it helpful?

Solution

Since symfony 2.3 country names can be translated using Intl and the RegionBundle.

The default returned array of getCountryNames() looks like this:

=> array('AF' => 'Afghanistan', ...)

If you're only interested in the country names use something like this:

use Symfony\Component\Intl\Intl;

// get all country names in locale "locale"
$countries = array_values(Intl::getRegionBundle()->getCountryNames('de'));

// get all country names for current locale
$countries = array_values(Intl::getRegionBundle()->getCountryNames());

... in case you just want to translate an array using the translator.

$translator = $this->get('translator');

foreach ($countries as $key => $country) {
    $countries[$key] = $translator->trans($country, array(), null, 'de');
}

See the Translator API Documentation and read the cookbook chapter Translations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top