Skip to content

Instantly share code, notes, and snippets.

@asiermarques
Created December 3, 2016 12:00
Show Gist options
  • Save asiermarques/6f036875c7be958e7e1de8349b8ae373 to your computer and use it in GitHub Desktop.
Save asiermarques/6f036875c7be958e7e1de8349b8ae373 to your computer and use it in GitHub Desktop.
Intl Twig localized filters
<?php
namespace AppBundle\Twig {
use Symfony\Component\Intl\Exception\RuntimeException;
class AppExtension extends \Twig_Extension
{
public function __construct()
{
if (!class_exists('IntlDateFormatter')) {
throw new RuntimeException('The intl extension is needed to use intl-based filters.');
}
}
/**
* Returns a list of filters to add to the existing list.
*
* @return array An array of filters
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('localizedlanguage', 'twig_localized_language_filter'),
new \Twig_SimpleFilter('localizedcountry', 'twig_localized_country_filter')
);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'app_extension';
}
}
}
namespace {
function twig_localized_language_filter($language_iso, $locale = null)
{
static $formatter;
$locale = $locale !== null ? $locale : \Locale::getDefault();
$formatter = \Locale::getDisplayLanguage ( $language_iso, $locale );
return $formatter;
}
function twig_localized_country_filter($country_iso, $locale = null)
{
static $formatter;
$locale = $locale !== null ? $locale : \Locale::getDefault();
$formatter = \Locale::getDisplayRegion('und_' . $country_iso, $locale );
return $formatter;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment