Get translated country name from a 2 digit country code in Symfony2/Twig?

Polmonino picture Polmonino · Mar 23, 2012 · Viewed 19.5k times · Source

I'm using the Symfony2 country Field Type, it works well and country names are translated. I am storing the two-digit country code in the column country of my entity.

How can I display the full, translated country name? This is how I added the field to the form:

$builder
    ->add('country', 'country', array(
        'label' => 'Paese', 'preferred_choices' => array('IT')
    ));

And then in my controller:

$user = $this->getDoctrine()->getRepository('AcmeHelloBundle:User');
$countryCode = $user->getCountry();
$countryName = null; // Get translated country name from code

Or in my twig template:

{# Output the country code and name #}
{{ user.country }}

{# translated country name from code #}

Answer

Hannoun Yassir picture Hannoun Yassir · Sep 1, 2013

I'm not sure if you still need... but it might help someone else. this can be done through a twig extension easily (this code is based on @tomaszsobczak's answer )

<?php
    // src/Acme/DemoBundle/Twig/CountryExtension.php
    namespace Acme\DemoBundle\Twig;


    class CountryExtension extends \Twig_Extension {
        public function getFilters()
        {
            return array(
                new \Twig_SimpleFilter('country', array($this, 'countryFilter')),
            );
        }

        public function countryFilter($countryCode,$locale = "en"){
            $c = \Symfony\Component\Locale\Locale::getDisplayCountries($locale);

            return array_key_exists($countryCode, $c)
                ? $c[$countryCode]
                : $countryCode;
        }

        public function getName()
        {
            return 'country_extension';
        }
    }

And in your services.yml files

# src/Acme/DemoBundle/Resources/config/services.yml
services:
    acme.twig.country_extension:
        class: Acme\DemoBundle\Twig\CountryExtension
        tags:
            - { name: twig.extension }

Usage example inside a twig file:

{{ 'US'|country(app.request.locale) }}