I am trying to implement the simplest and smallest “change language” widget in my small web app.
I will be using a plug that detects the locale stored in the session and calls Gettext.put_locale.
For this, I need a way for the user to set the locale.
I was thinking to add something in my sidebar, which is defined in the root layout.
Is it possible to add a live component or something else that puts a value into the session and then reloads the page?
The solution I use in the gist involves updating the session via Plug, and reading/sharing the locale between Plug (available in controllers) and LiveView using a global on_mount hook.
The other solution is to have a separate route for every locale. This might seem a lot of work but most of the heavy lifting can be done by a lib called Routex. It has several benefits over ‘setting session language + gettext’, one of them: instead of setting a session value, you can simply link to a localized page.
Since I didn’t need localized routes, I ended up trying your solution and it worked great.
The only issue I have with that is that when I change the language, I get redirected to the index page.
Maybe it is possible to work around this by doing an AJAX request? I don’t know if it can be done in LiveView. I think the current page may need to be reloaded also?
If you store the user language in your database, you might be able to simplify things.
You can update the database from a LiveView, without touching the session (which is by default backed by cookies which you need a regular HTTP resquest-response to set on the browser).
Maybe it is possible to work around this by doing an AJAX request? I don’t know if it can be done in LiveView. I think the current page may need to be reloaded also?
If you store the user language in your database, you might be able to simplify things.
You might reconsider picking the ‘simple solution’ as it already causes issues and asks for additional ‘less simple solutions’.
Here are a few additional thoughts:
Search engines love 1-url-per-locale. If the routes are behind a login, having localized routes may have less impact.
Have a look at Cldr Plug — Cldr Plug v1.3.3. This a great Plug with many options for locale retrieval; including non-session based.
I forgot to mention that the translation extension from Routex as mentioned in the tutorial is not required, if the additional translation work was a concern.