我正在使用 Symfony2 country Field Type ,效果很好,国家名称也被翻译了。我将两位数的国家/地区代码存储在我的实体的 country
列中。
如何显示完整的翻译国家/地区名称?这就是我将字段添加到表单的方法:
$builder
->add('country', 'country', array(
'label' => 'Paese', 'preferred_choices' => array('IT')
));
然后在我的 Controller 中:
$user = $this->getDoctrine()->getRepository('AcmeHelloBundle:User');
$countryCode = $user->getCountry();
$countryName = null; // Get translated country name from code
或者在我的 Twig 模板中:
{# Output the country code and name #}
{{ user.country }}
{# translated country name from code #}
最佳答案
我不确定您是否仍然需要...但它可能对其他人有帮助。这可以通过 Twig 扩展轻松完成(此代码基于@tomaszsobczak的答案)
<?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';
}
}
在你的 services.yml 文件中
# src/Acme/DemoBundle/Resources/config/services.yml
services:
acme.twig.country_extension:
class: Acme\DemoBundle\Twig\CountryExtension
tags:
- { name: twig.extension }
twig 文件中的使用示例:
{{ 'US'|country(app.request.locale) }}
关于symfony - 在 Symfony2/Twig 中从 2 位国家/地区代码获取翻译后的国家/地区名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9847092/