Textpattern tips, tutorials and code snippets

Multi-lingual articles in Textpattern

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 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 <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 = @$_SERVER['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.

4 Comments Comment feed

Great tip! Just a minute too late > www.waterlijf.nl … ;-)

Hi Joop. Glad you like the excellent tip. How is it a minute too late for you…?

Because the site was finished one minute (or so!) before the tip was published … and my time and her money were very limited at that moment!

but how do you create a feed for each language?

Add a comment

Use Textile help to style your comments