Skip to content

Instantly share code, notes, and snippets.

@elnygren
Last active January 16, 2020 15:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elnygren/160e2f702b270f6f8313bdd85b9fe2e0 to your computer and use it in GitHub Desktop.
Save elnygren/160e2f702b270f6f8313bdd85b9fe2e0 to your computer and use it in GitHub Desktop.
Simple ReasonML i18n internationalization example with strong static typing and JS/TS support with GenType
/** Schema for translations, with @genType for TS/JS usage */
[@genType]
type translations = {
helloMessage: string,
helloMessageWithVariable: (~name: string) => string,
};
/** English translations */
[@genType]
let translationsEN = {
helloMessage: "Hello there!",
helloMessageWithVariable: (~name) => "Hello there, " ++ name ++ "!",
};
/** Finnish translations need to use `{js|syntax|js}` due to funky letters */
[@genType]
let translationsFI = {
helloMessage: {js|"Hei siellä!"|js},
helloMessageWithVariable: (~name) => {j|"Hei siellä, $name!"|j},
};
/**
You can set language in your browser with
```javascript
localStorage.setItem('systemLang', 'fi');
```
*/
let systemLang =
Dom.Storage.getItem("systemLang", Dom.Storage.localStorage)->Belt.Option.getWithDefault("en");
/** Set systemLang in localStorage & reload page to apply change */
[@genType]
let setSystemLang = (lang) => {
Dom.Storage.setItem("systemLang", switch lang {
| `en => "en"
| `fi => "fi"
}, Dom.Storage.localStorage);
let reload: unit => unit = [%raw () => "window.location.reload();"];
reload();
};
/** helper for accessing translations */
[@genType]
let t =
switch (systemLang) {
| "fi" => translationsFI
| "en" => translationsEN
| _ => translationsEN
};
/** Usage: */
let message = t.helloMessageWithVariable(~name="Jaska")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment