【问题标题】:How to translate country names / a generic array in twig or controller in symfony2?如何在 symfony2 的树枝或控制器中翻译国家名称/通用数组?
【发布时间】:2013-09-12 12:28:14
【问题描述】:

我有一个包含所有国家/地区名称的数组,我想翻译这些名称,但我不知道如何

在我的控制器中我做了:

$countries = array("Afghanistan", "Albania", "Algeria", "Angola", ....);

return $this->render('xBundle:x:xs.html.twig', array('countries' => json_encode($countries))

在我的模板中我有:

List : {{countries}}

【问题讨论】:

  • 请不要在标题中使用伪标签。
  • 为什么要对视图参数进行 json 编码?直接给国家array('countries' => $countries)有什么问题?
  • 好的,但是我该如何翻译它们呢?
  • 您是否已经将翻译添加到您的应用程序中,您只需要知道如何使用 twig 翻译过滤器?
  • 其实一切都准备好了,但是我不知道如何翻译一个数组,我知道只有当它是一个字符串而不是数组时如何

标签: symfony translation twig icu


【解决方案1】:

由于 symfony 2.3 国家名称可以使用 Intl 和 RegionBundle 进行翻译。

getCountryNames() 默认返回的数组如下所示:

=> 数组('AF' => '阿富汗', ...)

如果您只对国家/地区名称感兴趣,请使用以下内容:

use Symfony\Component\Intl\Intl;

// get all country names in locale "locale"
$countries = array_values(Intl::getRegionBundle()->getCountryNames('de'));

// get all country names for current locale
$countries = array_values(Intl::getRegionBundle()->getCountryNames());

...如果您只想使用翻译器翻译数组。

$translator = $this->get('translator');

foreach ($countries as $key => $country) {
    $countries[$key] = $translator->trans($country, array(), null, 'de');
}

查看Translator API Documentation 并阅读cookbook chapter Translations

【讨论】:

    猜你喜欢
    • 2015-03-08
    • 2012-04-08
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2013-08-22
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多