问题描述
我正在使用 Symfony2 国家字段类型,它运作良好,国名被翻译.我在实体的 country
列中存储了两位数的国家/地区代码.
I'm using the Symfony2 country Field Type, it works well and country names are translated. I am storing the two-digit country code in the column country
of my entity.
如何显示完整的翻译过的国家/地区名称?这是我将字段添加到表单的方式:
How can I display the full, translated country name? This is how I added the field to the form:
$builder
->add('country', 'country', array(
'label' => 'Paese', 'preferred_choices' => array('IT')
));
然后在我的控制器中:
$user = $this->getDoctrine()->getRepository('AcmeHelloBundle:User');
$countryCode = $user->getCountry();
$countryName = null; // Get translated country name from code
或者在我的树枝模板中:
Or in my twig template:
{# Output the country code and name #}
{{ user.country }}
{# translated country name from code #}
推荐答案
我不确定您是否仍然需要...但它可能对其他人有所帮助.这可以通过树枝扩展轻松完成(此代码基于@tomaszsobczak 的回答)
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';
}
}
在你的 services.yml 文件中
And in your services.yml files
# src/Acme/DemoBundle/Resources/config/services.yml
services:
acme.twig.country_extension:
class: Acme\DemoBundle\Twig\CountryExtension
tags:
- { name: twig.extension }
twig 文件中的使用示例:
Usage example inside a twig file:
{{ 'US'|country(app.request.locale) }}
这篇关于从 Symfony2/Twig 中的 2 位国家代码获取翻译的国家名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!