Multi-lingual articles in Textpattern: A poor man’s solution

17. August 2008

As it goes for multi-lingual Textpattern powered sites, a full-fledged solution like Textpattern MLP supports a truly babylonian site architecture, from articles straight through to section names and random text snippets.

Sometimes this is just too much. I, for instance, had to fulfill an occasional need for a both German and English representation of the same content as I did a short writeup on my first WordPress plugin, wet_maintenance (which in turn is a transfer of Ruud’s concept in rvm_maintenance to the WordPress world).

The idea is to put all localized renditions of a text into just one article and let Textpattern conditionally render either one or the other part of it, depending on the user-agent’s Accept-Language preference.

All sample code below assumes Textpattern 4.0.7, as it makes use of the new <txp:variable /> tag.

A form wisely named accept-language establishes a default language preference, tries to sniff out the visitor’s language preferences subsequently, and finally stores the resulting language code into a Textpattern variable:

<txp:php>
variable(array('name' =>'accept-language', 'value' => 'de'));
$al = serverSet('HTTP_ACCEPT_LANGUAGE');
if (preg_match('/(.*?)[,;-]/', $al, $a)) {
    variable (
        array (
              'name' =>'accept-language', 
              'value' => $a[1]
        )
    );
}
</txp:php>

This form is placed somewhere above the content in question, either in the page’s template or at the very beginning of the article. Inside the article’s body, each localized fraction is surrounded by <txp:if_variable name="accept-language" value="LANGCODE"> tags. LANGCODE is one of the ISO languages codes like de, en, fr.

<txp:output_form form="accept-language" />
<txp:if_variable name="accept-language" value="de">

German content goes here...

<txp:else />

Non-german content goes here...

</txp:if_variable>

That’s all. For a live example, try visiting this article with different language preferences. All settings but de-* would render an English version.

Kommentare

  1. Neat solution, very simple.

  2. Although Textpattern MLP is the way to go for a true multilingual site, it’s nice to see there are other approaches to bi/multi-lingual sites using just TXP core (probably, with the help of a few neat plugins, or even without them).

    I love the MLP, but once, I needed to do a TXP site without it because the hosting didn’t match the MySQL requirements (> 4.1).

    So I also take my own approach to a bilingual site using sections as languages (/en/, /es/) and custom fields as a way to “connect” the translations.
    I also used zem_redirect 1.2 and asy_wondertag, if I’m not wrong.

    The result is here: Inti Huasi Hostel – Your home at Salta :)