gren i18next - Load and use translations at runtime
Functions for working with dynamically loaded translations in Gren.
Simple Example
gren package install gilramir/gren-i18next
Then use the module in your app like this.
In JS do:
// translations is a JSON string or JS object
Gren.Main.init({ flags: translations });
Then in gren, you use them in the init function of your app:
import Html exposing (Html)
import I18Next exposing
( t
, tr
, Translations
, Delims(..)
, translationsDecoder
)
import Json.Encode
import Json.Decode
type alias Model = {
translations: Translations
}
type Msg = ..
init : Json.Encode.Value -> { model: Model, command: Cmd msg}
init flags =
case Json.Decode.decodeValue translationsDecoder flags of
Ok translations ->
{ model = Model translations, command = Cmd.none }
Err err ->
-- handle the error
{- Imagine your translations file looks like this:
{
"hello": "Hallo",
"greetings": {
"goodDay": "Good day.",
"greetName": "Hi {{name}}"
}
}
-}
view : Model -> Html Msg
view model =
div []
[ div [] [ text (t model.translations "hello") ] -- "Hallo"
, div [] [ text (t model.translations "greetings.goodDay") ] -- "Good day."
, div [] [ text (t model.translations "nonExistingKey") ] -- "nonExistingKey"
, div [] [ text (tr model.translations Curly "greetings.greetName" [("name", "Peter")]) ] -- "Hi Peter"
]
Check out more complete examples here
Fetching Translations
If you can't pass the translations as flags but want to fetch them from Gren code instead do the same as in the simple example but apply the decoder to the Http call.
Embedded Translation
Or, if your application has a small set of translations and you don't mind every user having every translation loaded into their browser, you can generate the translations directly in Gren code. For example:
ko_translations =
fromTree
[
{ label = "greeting"
, item = object
[ { label = "hello", item = string "안녕하세요" } ]
}
]
Advanced Stuff: Placeholders and fallback languages
Here are some supported features for advanced use cases:
- Support for string placeholders
- Support for non-string placeholders such as
Html - Fallback languages
Check the official docs for usage examples.
History
This package was ported from the excellent elm-i18next package for Elm, written by Christoph Pölt.
In Cristoph's words regarding the background of that package:
Dealing with Translations in Elm has always come with some hoops to jump through. Existing solutions include tricks like passing already translated strings into the elm app as flags or generating Translation modules as a pre-build step like here or here.
Inspired by the i18next client in from the JS world. This elm module
allows you to load JSON translation files via HTTP and then use the
data in your Elm app. This should allow for a easier-to-use
internationalization as existing solutions.