Last active
March 25, 2019 13:49
-
-
Save mylk/d0690137c1fba25993211b9f301d1afb to your computer and use it in GitHub Desktop.
Twig extension that adds a filter that returns the country name by its 2-letter ISO code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Installation: | |
* ============= | |
* # services.yml | |
* services: | |
* # ... | |
* acme.twig.country_extension: | |
* class: Acme\AcmeBundle\Twig\CountryExtension | |
* tags: | |
* - { name: twig.extension } | |
* | |
* Usage: | |
* ====== | |
* {{ entity.countryCode | country }} | |
*/ | |
namespace Acme\AcmeBundle\Twig; | |
use Symfony\Component\Intl\Intl; | |
class CountryExtension extends \Twig_Extension | |
{ | |
public function getFilters() | |
{ | |
return array( | |
new \Twig_SimpleFilter("country", array($this, "countryFilter")), | |
); | |
} | |
public function countryFilter($countryCode, $locale = "en") | |
{ | |
\Locale::setDefault($locale); | |
$countryName = ""; | |
if ($countryCode) { | |
$countryName = Intl::getRegionBundle()->getCountryName($countryCode); | |
} | |
return $countryName ?: $countryCode; | |
} | |
public function getName() | |
{ | |
return "country_extension"; | |
} | |
} |
Works great! Many thanks.
Had to remove \Locale::setDefault($locale);
to get my default locale.
Super, Thanks!
Just add strtoupper in case of country code small letters.
$countryName = Intl::getRegionBundle()->getCountryName(strtoupper($countryCode));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Many thanks for sharing this :) !
It should be officially added in Twig Extension repo