symfony - 在 Symfony2/Twig 中从 2 位国家/地区代码获取翻译后的国家/地区名称?

标签 symfony twig symfony-forms

我正在使用 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/

相关文章:

symfony - 渲染包含文件类型的 Symfony 4 编辑表单时出错

php - api 平台 - 无法为项目生成 IRI

php - Symfony2 - 没有 session cookie 的有状态 API key 身份验证

php - 限制最大高度的文本

php - Symfony2.8 如何构建一个可以从所有模板查看的搜索表单

php - Symfony2 和 Selectize.js : Clearest way to persist new items in entity field type?

php - 如何给symfony写权限

php - socket_create_listen 不适用于 Windows 中的所有接口(interface)

PHP Twig 日期(H :i:s) from seconds

symfony - 如何设置请求 symfony 的内容?