I set up the translation with symfony 6 and the intl package (also intl-extra), everything works perfectly, now I'd like to add the ability to switch language, so I've added this to my twig template:
我用symfony 6和intl包(也是intl-extra)设置了翻译,一切都很完美,现在我想添加切换语言的功能,所以我把这个添加到我的twig模板中:
<ul class="dropdown-menu">
{% for locale in locales() %}
{% set is_active = app.request.locale == locale.code %}
{% set english_flag = locale.code == 'en' ? 'gb' : locale.code %}
<li class="{{ is_active ? 'active' }}" translate="no">
<a class="dropdown-item" lang="{{ locale.code }}" hreflang="{{ locale.code }}" href="#">
<img src="https://flagcdn.com/{{ english_flag }}.svg" alt="English flag" width="20"/>
{{ locale.name|capitalize }}
</a>
</li>
{% endfor %}
</ul>
I'd like to add flags (with a CDN), but there is no official flag for the English language which is not a country, so I have to define a variable and ternary operator to change the en letter code to gb to display the correct flag. However, I don't like this approach. Is there another way? How do you do it?
我想添加标志(带有CDN),但对于不是国家的英语没有官方标志,所以我必须定义一个变量和三元运算符,将en字母代码更改为GB以显示正确的标志。然而,我不喜欢这种方法。还有别的办法吗?你是怎么做到的?
Ideally, I imagine we'd have to create a class grouping all locale code English-speaking countries?
理想情况下,我想我们必须创建一个将所有地区代码为英语的国家分组的类?
更多回答
优秀答案推荐
I've found a more interesting solution, but I understand that the flag-based language system is not recommended, many countries speak English, so which flags to display ..
我找到了一个更有趣的解决方案,但我知道不建议使用基于国旗的语言系统,许多国家都说英语,所以应该展示哪些国旗。
Here's my solution for the moment, I've added a twig filter that allows me to define certain rules depending on the locale:
以下是我目前的解决方案,我已经添加了一个小枝过滤器,它允许我根据区域设置定义某些规则:
public function getFlag(?string $flag): string
{
switch ($flag) {
case 'en':
case 'us':
$countryCode = 'gb';
break;
default:
$countryCode = $flag;
}
return $countryCode;
}
And the twig template:
和小树枝模板:
<ul class="dropdown-menu">
{% for locale in locales() %}
{% set is_active = app.request.locale == locale.code %}
<li class="{{ is_active ? 'active' }}" translate="no">
<a class="dropdown-item" lang="{{ locale.code }}" hreflang="{{ locale.code }}" href="#">
<img src="https://flagcdn.com/{{ locale.code|flag }}.svg" alt="" width="20"/>
{{ locale.name|capitalize }}
</a>
</li>
{% endfor %}
</ul>
if anyone has a better solution, please do not hesitate.
如果有人有更好的解决方案,请不要犹豫。
更多回答
我是一名优秀的程序员,十分优秀!