How to add two letter gb flag to all english languages in symfony 6?

79 Views Asked by At

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:

<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?

Ideally, I imagine we'd have to create a class grouping all locale code English-speaking countries?

1

There are 1 best solutions below

0
Momonosoke On

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.