Skip to content

Instantly share code, notes, and snippets.

@mylk
Last active March 25, 2019 13:49
Show Gist options
  • Save mylk/d0690137c1fba25993211b9f301d1afb to your computer and use it in GitHub Desktop.
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
<?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";
}
}
@MlleDelphine
Copy link

Many thanks for sharing this :) !
It should be officially added in Twig Extension repo

@leperse
Copy link

leperse commented Nov 22, 2017

Works great! Many thanks.

Had to remove \Locale::setDefault($locale); to get my default locale.

@AlaaKanaan
Copy link

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