Change html lang attribute when locale changes
Asked Answered
A

2

3

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 to achieve this?

PS: my ultimate goal is to be able to switch font for different languages (chinese looks just too bad with the font I chose for english). I am thinking of using the CSS :lang() pseudo selector: html:lang(zh)

Askwith answered 30/1, 2013 at 4:24 Comment(0)
S
10

Asuming you are using html5 and twig as template engine:

<!doctype html>

<html lang="{{ app.request.locale }}">

...
Stonedeaf answered 31/1, 2013 at 4:50 Comment(1)
That was so obvious and yet I didn't think of it.. Thanks! Now I'll work on how to change the font based on the language used.Askwith
F
1

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:

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

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

Fujio answered 29/5, 2015 at 20:29 Comment(4)
lang attribute accepts full locale, just like elements in HTTP Accept-Language headerConsequence
But they must be separated with a dash rather than an underscore, e.g. en-cockney. w3.org/TR/html401/struct/dirlang.html#h-8.1.1Fujio
ah true. But I'd leave the country code when it's provided: | replace({'_', '-'})Consequence
Correct syntax according to my twig is {{ app.request.locale | replace({'_': '-'}) }}Northcliffe

© 2022 - 2024 — McMap. All rights reserved.