Multi-Language Page
Defaults
English is the default language.
If there is a language query param in the URL, it will respect its value. For example /contact?language=de.
The language can also be set in context.session.
Simple usage
To be able to use the translations feature, there has to be at least one translation file present.
In this example, we will use the page translation key in two languages to demonstrate the mechanism.
---
slug: multilanguage
---
{{ 'general.greeting' | t }}
app/translations/en.yml
en:
general:
greeting: Hello, World!
app/translations/pl.yml
pl:
general:
greeting: Witaj świecie!
Having these two files enables you to use the t filter. t stands for translate, and you can use both.
For example, opening /multilanguage will default to English. Opening /multilanguage?language=pl will try to use Polish and fall back to English for keys that haven't been found.
/multilanguage
Hello, World!
/multilanguage?language=pl
Witaj świecie!
Arrays
Inside YAML, it is possible to include any data structure that is usable in JSON, including arrays.
See json2yaml to see how YAML will convert to JSON or vice-versa if you feel more comfortable in JSON.
You can use this feature alongside other filters to store collections in a readable form.
app/translations/en.yml
en:
general:
cars:
- Ford Mustang
- Corvette
- Gran Torino
app/translations/jp.yml
jp:
general:
cars:
- Honda
- Subaru
- Lexus
Example page
{% assign cars = 'general.cars' | t | to_hash %}
<ul>
{% for car in cars %}
<li>{{ car }}</li>
{% endfor %}
</ul>
/multilanguage?language=en
<ul>
<li>Ford Mustang</li>
<li>Corvette</li>
<li>Gran Torino</li>
</ul>
/multilanguage?language=jp
<ul>
<li>Honda</li>
<li>Subaru</li>
<li>Lexus</li>
</ul>
Parameterization (variables)
Sometimes you'll need to translate parts of a sentence, but keep others (e.g. names). In these cases, some of the content should be parameterized.
The translate filter accepts named arguments and %{variable} syntax is available in translations keys.
app/translations/en.yml
en:
personal:
hello: 'Hello %{name}. Take a look at my website: %{url}'
app/translations/pl.yml
pl:
personal:
hello: 'Cześć %{name}. Zerknij na moją stronę www: %{url}'
Example page
{% assign my_name = context.params.name | default: "Pawel" %}
{% assign url = context.params.url | default: "https://example.com" %}
{{ 'personal.hello' | t: name: my_name, url: url }}
/multilanguage?language=en&name=John&url=https://documentation.platformos.com
Hello John. Take a look at my website: https://documentation.platformos.com
/multilanguage?language=pl&name=Pawel&url=https://platform-os.com
Czesc Pawel. Zerknij na moja strone www: https://platform-os.com
Live example and source code
Compilation of all examples above:
Source code can be found on GitHub.