什么是使Elm应用程序国际化的好方法?

jm.*_*jm. 11 elm

我需要将ELM HTML应用程序中的UI字符串国际化为3种不同的语言.

我在想这样做:

1)我将从Javascript获取currentLanguage,并在ProgramWithFlags中传递它.我会保持模型中的语言

2)我将在我的代码中设置一些类型

type alias Languages = English | French | Spanish
-- One of these for each string I want to internationalize
type alias InternationalizedStrings = StringHello | StringFoo | StringBar
Run Code Online (Sandbox Code Playgroud)

3)我将创建一个函数,用于返回在我的视图中使用的每个翻译短语.

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"
      ...
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?我有很多字符串.

pie*_*itz 4

如果您在不提供字符串翻译时希望出现编译器错误,那么您的解决方案是正确的。

如果您想允许尚未翻译的字符串,或者发现为每个可翻译字符串指定一个类型很乏味,您可能需要切换到Dict基于 - 的解决方案。要修改它,只需将其放入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)
Run Code Online (Sandbox Code Playgroud)