Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to internationalize an Elm application?

Tags:

elm

I need to internationalize the UI strings in my ELM HTML application to 3 different languages.

I am thinking of doing this:

1) I will get the currentLanguage from Javascript, and pass it down in the ProgramWithFlags. I'llkeep the language in the model

2) I'll setup some types in my code

type alias Languages = English | French | Spanish
-- One of these for each string I want to internationalize
type alias InternationalizedStrings = StringHello | StringFoo | StringBar

3) I'll make a function for returning each translated phrase to use in my Views.

getPhrase: InternationalizationString Languages -> string
getPhrase stringId lang = 
   case lang of
      English ->
           case stringId of
              StringHello -> "Hello"
              StringFoo -> "Foo"
              StringBar -> "Bar"
      French ->
           case stringId of
              StringHello -> "Bonjour"
              StringFoo -> "Oui"
              StringBar -> "Non"
      ...

Is there a better way to do this? I have lots of string.

like image 383
jm. Avatar asked Oct 27 '16 00:10

jm.


1 Answers

In case you want compiler errors when you don't provide the translation for a string your solution is on the right track.

If you want to either allow yet untranslated strings or find it tedious to have a type for every translatable string, you might want to switch to a Dict-based solution. to tinker with it, just throw it into http://elm-lang.org/try:

import Dict exposing (Dict)
import Html exposing (text)


type Language
    = English
    | French
    | Spanish


type alias Key =
    String


main =
    text <| translate French "Hello"


translate : Language -> Key -> String
translate lang key =
    let
        dict =
            case lang of
                English ->
                    Dict.fromList
                        [ ( "Hello", "in english" )
                        ]

                French ->
                    Dict.fromList
                        [ ( "Hello", "salut" )
                        ]

                Spanish ->
                    Dict.fromList
                        [ ( "Hello", "hola" )
                        , ( "someKeyThatOnlyExistsInSpanish", "42" )
                        ]
    in
        Dict.get key dict |> Maybe.withDefault ("can not find translation for " ++ key)
like image 137
pierrebeitz Avatar answered Sep 19 '22 12:09

pierrebeitz