I try to offer as much of the content on my website as possible in multiple languages. The translation and internationalisation interfaces of my content management system Kirby help me to do this. They make it easy to create multilingual content.
Recently, however, I encountered a small problem that took more time to solve than I had expected.
It is about the integration of the language switcher, which is located at the bottom of each page and contains a link to the current page in another language version:
Diese Seite gibts auch auf Deutsch.
To do this, I first added a new entry in the corresponding translation file under site/language/$lang_code.php
for the languages I want to support (in my case German and English):
Next, I created the following snippet in the file site/snippets/language_switch.php
:
In this code there are some interesting Kirby functions are linked together:
- First, all languages that are available in Kirby are run through in a loop, skipping the language that the page is currently viewed in.
- Next, the URL of the current page is searched for in another language. We get this by calling the auxiliary function
$page->url()
with a parameter and passing it the target language:$page->url($language->code())
. - If necessary, all
$_GET
request parameters are also passed through to the new URL. - We use the
lang
attribute to tell the browser that the text is written in a different language from the rest of the document. The helper function$language->code()
helps us with this, - Finally, we use the function
I18n::template()
to output the translated text in the target language. In addition, we also replace{language_name}
with the name of the language and{language_name}
with the URL of the language version. The functiont()
, which I usually use to translate template strings, unfortunately does not allow us to make substitutions.
The snippet is then used in all my templates via snippet('language_switch');
.
Leave a comment
Replied on your own website? Send a Webmention!