MithrilJS simple localization
Introduction
When I first started learning Mithril.js, I focused on getting things to just work. But as the app grew, I realized it needed localization—the ability to display text in different languages.
If you’ve ever worked on a multi-language app, you know it can be messy: scattered strings, hard-coded labels, and a growing list of “Where is that text coming from?” moments.
So I built a simple, reusable localization module for my Mithril.js project. In this post, I’ll walk you through how it works, how I store translations, and how I use them in my views.
The idea
The goal was simple:
- Keep translations in JSON files.
- Store the current language in localStorage so it persists.
- Load translations only when needed.
- Use a short
i18n.t('some.key')
syntax to fetch text.
The Localization Module
Here’s the core of the implementation:
|
|
How It Works
defaultLocale
is the fallback language (e.g., “ja”).
messages
is where all loaded translations are stored.
init()
- Runs on app start, checks if a language is saved in localStorage.
- If yes → loads that language.
- If no → loads the default locale.
t(key)
: Gets a translation by its dot-separated path.
|
|
setLocale(newLocale)
- Prevents reloading if the language is already active.
- Replaces
{locale}
in the URL template with the selected language. - Saves the chosen locale to localStorage.
- In development, adds a timestamp query (
?v=...
) to avoid browser caching. - Fetches the JSON file and stores it in
messages
.
The Language Files
Here’s an example of my message.ja.json
:
|
|
I keep one file per language, for example:
message.ja.json
message.en.json
Using It in a View
Here’s how you use it in a Mithril view:
|
|
Conclusion
This approach keeps localization simple and maintainable by separating translation data from the application logic and loading only what’s needed. While it works well for my current needs, it’s far from perfect — for example, adding browser default language detection could make it even better.