There are many ways to add multiple languages to your web site. You will certainly know how you do it. But still... I came up with a new alternative, which I see as a light weight alternative, suitable especially for small web sites.

Markup for easy l10n

My solution uses the "lang" attribute, which is part of the HTML4 specification. You mark up "alternative" content of your website with the lang attribute, in the following way:

<p>This is the base language content</p>
<p lang="de">Das ist der Inhalt in deutsch</p>

and may do so multiple times on a web page. The only rule: the pieces of alternate content must be siblings. On page load a small piece of javascript takes over and chooses which part of the content to show, and hides all other content. A sample implementation (as a jQuery plugin) can be found here. The code honors node names (<p>, <div>, etc.) and class names to check for matching siblings. So this would work fine:

<div>
  <p class="first">First paragraph</p>
  <p class="first" lang="de">Erster Absatz</p>
  <p class="second">Second paragraph</p>
  <p class="second" lang="de">Zweiter Absatz</p>
</div>

while the following (currently) does not:

<div>
  <p>First paragraph</p>
  <p lang="de">Erster Absatz</p>
  <p>Second paragraph</p>
  <p lang="de">Zweiter Absatz</p>
</div>

Choosing a language

To select a specific language use the following:

jQuery.ez_localize("body", "de");

The first parameter defines the scope for localization. It defaults to "body". To skip the localization code completely just run jQuery.ez_localize(null). The second parameter defines the language. The default is null, which selects the "base language", i.e. those parts of the page without a "lang" attribute.

To set the language at a later time just use the same piece of code again. This way your users can switch between languages at any time.

CSS Changes

To hide the extra content even if the user has Javascript turned off you must add a

[lang] {
  display: none;
}

rule to your stylesheet. This is a CSS3 selector - I honestly don't know which browsers do implement this already.

Pros & Cons

Pros:

  • Easily deployed: just add content in the alternative languages of your choice: if you can modify the HTML content on your site, you can add translations with this.
  • One document to bind them all: don't change the overall structure of your site, don't change URLs.
  • Change the language in the browser: no server traffic

Cons:

  • Only a light weight solution.
  • One document binds them all: this is not how the web usually works. Usual best practices are different.