Last active
January 16, 2020 15:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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