elm-translations
Generate type safe translations for your Elm app
elm-translations
is a command line script that generates an Elm module from your JSON translation files. This module just includes a Translations
type (nested Record), a JSON decoder and a JSON parser, but not the actual translation data. So you just need to generate the Elm code once and then use it for all the languages you want to support in your app by e.g. loading them dynamically at runtime.
Features
✅ Type safe
Won't compile if you try to access the wrong keys in your Elm code
✅ Nesting support
Let's you organize your translations easily
✅ Variable substitutions
Just pass a Record and never forget to set a variable again
Usage
# get a preview of the generated Elm code $ npx elm-translations --from your-translations.json # generate Elm code and store it here: ./src/Translations.elm $ npx elm-translations --from your-translations.json --out src # or use a custom module name - will be stored here: ./src/I18n/Trans.elm $ npx elm-translations --from your-translations.json --module I18n.Trans --out src # see all possible options $ npx elm-translations --help Type safe translations
Examples
flags
Passing translation data via - Create your
Translations.elm
file with e.g.:
$ npx elm-translations -f en.json -o src
- In your Html page pass the translation data:
......
- In your Elm app use the translations:
module Main exposing (..) import Json.Decodeimport Json.Encodeimport Translations exposing (Translations) -- ... type Model = Initialized Translations | Failed Json.Decode.Error init : Json.Encode.Value -> ( Model, Cmd Msg )init flags = case Translations.parse flags of Ok t -> ( Initialized t, Cmd.none ) Err error -> ( Failed error, Cmd.none ) view : Model -> Html Msgview model = case model of Initialized t -> div [] [ h1 [] [ text <| t.welcome { name = "John" } ] , p [] [ text t.home.intro ] ] Failed error -> p [] [ text "Error: Cannot proccess translation data" ] -- ...
Dynamically fetching translation data
There's an example available in the git repository. To let it run locally on your machine, follow these steps:
- Clone the respository
$ git clone git@github.com:layflags/elm-translations.git
- Go to the example folder
$ cd elm-translations/example
- Generate the
Translations.elm
module
$ npx elm-translations --from en.json --out src
- Start Elm Reactor and go to http://localhost:8000/src/Main.elm
$ elm reactor
Or just visit: https://elm-translations-example.surge.sh/
JSON file requirements
Use only lower camel case keys!
🟢 YES
🔴 NO
Use only lower camel case variables!
🟢 YES
🔴 NO
String
values (nesting possible)!
Use only 🟢 YES
🔴 NO