Get translated country name from a 2 digit country code in Symfony2/Twig?
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.ymlservices: acme.twig.country_extension: class: Acme\DemoBundle\Twig\CountryExtension tags: - { name: twig.extension }
Usage example inside a twig file:
{{ 'US'|country(app.request.locale) }}
As per @Rvanlaak's comment above, \Symfony\Component\Locale\Locale is now deprecated. I think the most concise way to do this now is:
use Symfony\Component\Intl\Intl;...$country = Intl::getRegionBundle()->getCountryName($countryCode);
Inspired by Hannoun Yassir answer, I use the Intl as in the country type field.The code of twig extension is
<?phpnamespace Tbl\SagaBundle\Twig;use Symfony\Component\Intl\Intl;class CountryExtension extends \Twig_Extension{ public function getFilters() { return array( new \Twig_SimpleFilter('countryName', array($this, 'countryName')), ); } public function countryName($countryCode){ return Intl::getRegionBundle()->getCountryName($countryCode); } public function getName() { return 'country_extension'; }}?>
Add twig extension in services.yml
# src/Acme/DemoBundle/Resources/config/services.ymlservices: acme.twig.acme_extension: class: Acme\DemoBundle\Twig\CountryExtension tags: - { name: twig.extension }
usage in the template (the country name will be display in locale by default (see Symfony/Component/Intl/ResourceBundle/RegionBundleInterface.php)
{{ user.countryCode|countryName }}
Many thanks Yassir, this version don't use locale deprecated since version 2.3 >> http://symfony.com/components/Locale