Skip to content Skip to sidebar Skip to footer

Change Html Lang Attribute When Locale Changes

I have a multilangual website running with PHP/Symfony2. I would like to change the html lang attribute when the user switches language (= switching locale). What is the best way t

Solution 1:

Asuming you are using html5 and twig as template engine:

<!doctype html><htmllang="{{ app.request.locale }}">

...

Solution 2:

The recommended way of storing locales is language code underscore country code, e.g. en_GB.

The term locale refers roughly to the user's language and country. It can be any string that your application uses to manage translations and other format differences (e.g. currency format). The ISO 639-1 language code, an underscore (_), then the ISO 3166-1 alpha-2 country code (e.g. fr_FR for French/France) is recommended. http://symfony.com/doc/current/book/translation.html

Therefore, a safe way of using the locale in the lang attribute would be:

<htmllang="{{ app.request.locale|split('_')[0] }}">

This works with both an en_GB locale and an en locale.

Post a Comment for "Change Html Lang Attribute When Locale Changes"