I continue with my notes regarding my app for encrypting and decrypting text messages (DoCrypt.org). I decided to use two languages, Italian and English. But I intend to add more languages in the future. I have chosen to create a specific component to manage the different languages. I think it’s an easy way to build multilingual apps. In this post I talk about how to create a multilingual component with Svelte.
I use Svelte, because it’s simple. It can also translate all the components of the application in real time.
The idea is simple: I create a component to display the text in a specific language. To decide in which language, I use a store, which is a general variable that I can access from any other component. This way, if I decide to change the language, all the components that show some text update automatically.
This way, I can change the language anywhere in the application, simply by using lang.set("it")
or lang.set("en")
.
The second step is to create a dictionary. I can use various techniques, but for a small project one object is enough.
At the first level I enter the name of the page that is displayed (for example, Home
), at the second level a string that identifies the text I want to show (for example, Encrypt
), at the third level the translation identified by the language (for example, en
).
Now I can access the translation of a string on a specific page, using languages.Home.Encrypt.en
or languages.Home.Encrypt.it
.
Finally I need a component whose only job is to read the string value and insert it into another component:
Instead of {languages[p][w][$lang]}
I can use {@html languages[p][w][$lang]}
to use HTML tags in the string. I think it’s a good idea to translate some text with some formatting or links. But for simple text such as button labels this is not necessary.
To use this component, I can use code similar to this:
Save the settings
The problem is that the user has to manually reset the language each time they visit the site. To fix this, I can save the user’s preferred language in the browser. When the user visits the site, he uses his preferred language.
To do this I can use Jake Archibald’s IDB-Keyval library. This library allows you to save and read values from a local database.
I add the library to my project:
npm install idb-keyval
So I create a new file
I use the setLang
function to set the default language. I also use getLang
to read the preferred language from the browser memory. If the user has never set a language, the getLang
function will return the browser language.
Then I modify the Svelte store to apply any changes to the local database:
Finally I change the main page of the app to read the preferred language on startup:
Well, that’s all for now. If you want to see the full code, you can find it on GitHub. The application is available on docrypt.org.