Textpattern tips, tutorials and code snippets

Easy multilingual navigation

This tip originated in response to a forum question. Suppose that you are developing a site for a multilingual audience, but most articles contain just images and a few descriptions that don’t need to be translated. You wish, however, to give your visitors the possibility to choose a language, and to include some language-specific element (say, a localised navigation bar) in every page.

We will do it by appending to every link some lang URL parameter corresponding to the chosen language, and outputting the corresponding navigation bar. Here is the plan.

Create navigation forms

First, we create one navigation form per language (menu-fr, ... , menu-ru), like this:

<a href="/paintings/">Paintings</a> ... <!-- default menu- form -->
<a href="/paintings/?lang=fr">Tableaux</a> ... <!-- menu-fr form -->
...
<a href="/paintings/?lang=ru">Картины</a> ... <!-- menu-ru form -->

The page form will include a list of links that allow visitors to switch between languages:

<a href="/">English</a><a href="?lang=fr">Français</a> ... <a href="?lang=ru">Русский</a>

Output the navigation menus

Next, we output the menu corresponding to the value of lang URL parameter. This value can be retrieved with the adi_gps plugin, but we will use etc_url here, since we will need it later anyway:

<txp:variable name="lang" value='<txp:etc_url type="lang" />' />
<txp:output_form form='menu-<txp:variable name="lang" />' />

So, every time the user clicks on a link containing lang=ru, the Russian navigation bar will be output. The problem is that the internal (article, section, category, …) links produced by Textpattern will not preserve this parameter, and clicking on the /paintings/mona-lisa link will bring us the default (English) menu.

Rewrite internal links

That is what etc_url was created for: rewrite internal links as needed. It suffices to replace <txp:permlink /> in article forms with:

<txp:etc_url context="article" query='lang=<txp:variable name="lang" />'>
	<txp:title />
</txp:etc_url>

This will transform /paintings/mona-lisa into /paintings/mona-lisa?lang=ru on a Russian page. You can do the same for section and category links, so the lang parameter will be automatically transmitted from one page to another.

Further tweaks

You could add some tweaks, like an initial language choice based on the value of HTTP_ACCEPT_LANGUAGE server parameter. You could also replace <a href="?lang=ru">Русский</a> in the language switching menu by using the following code:

<txp:etc_url query='lang=<txp:variable name="lang" />'>Русский</txp:etc_url>

The above code will ensure that you stay on the same page when choosing another language. Finally, other content (like custom fields) could be localised following the value of lang parameter.

Enjoy, and Merry Christmas | Joyeux Noël | Счастливого Рождества!