Reputation: 27
I am asking this purely for educational purposes, while browsing for some reference information for HTML5, I came across the lang
attribute, while I understand its a way of defining a language, if I were to say make a multi language site, rather than make every page again I would have assumed it would be a way to hide various divs based on the language of the browser i.e.
<div lang='en'>Hello</div>
<div lang='ja'>こんいちは</div>
So my first thought was if my browser was set to english it should show only the english tag, however upon further reading it seems that the lang
tag only seems to tell the browser what language it is and added support for TTS, Braile, and other things.
Is this correct, or am I just being oblivious to some other underlying use of it?
If it is just a reader or something similar, would the best way of swapping languages on a single html/php site be:
<?php if ($_GET['lang'] == "en") { ?>
<div>Hello</div>
<?php } else if ($_GET['lang'] == "ja") { ?>
<div>こんいちは</div>
<?php } else { ?>
<div>Language not supported</div>
<?php } ?>
While I have been a programmer for many years, there are many small things like this that I have simply not come across before.
Regards
Upvotes: 0
Views: 3634
Reputation: 4028
You could use CSS to show or hide elements depending on their lang
attribute. You would just waste a lot of bandwidth.
The purpose of the language tag is to enable you to mark links, quotes or the like, so you can style them, e.g., add a british flag to a link that points to an English article from your Japanese blog post, and to enable screen readers to provide the correct pronounciation.
If you want to provide translated text depending on a parameter, you should do the translation outside of your HTML code (just like any other processing). The mix just makes code illegible and a maintenance nightmare.
A common solution is to provide translation data in separate language files, mostly .ini
files. In your case, they could look like:
languages/ja.ini
:
LANG="ja"
HELLO="こんいちは"
languages/en.ini
:
LANG="en"
HELLO="Hello"
Now, you can use those in your HTML files.
index.php
:
<?php
$language = $_GET['lang'] ?: 'en';
$translation = "languages/{$language}.ini";
if (!is_readable($translation)) {
throw new \RuntimeException("Language file {$translation} not found");
}
$_ = parse_ini_file($translation);
?>
<div lang="<?= $_['LANG']; ?>"><?= $_['HELLO']; ?></div>
Both your PHP and HTML code are easier to understand, and the language files are easy to maintain.
Upvotes: 1