Use common variable in Url.Parser in all URLs for language code

We are using a parser similar to this one:

parser : Parser (Route -> a) a
parser =
    oneOf
        [ Parser.map Home Parser.top
        , Parser.map About (s "about")
        , Parser.map Login (s "login")
        , Parser.map Logout (s "logout")
        , Parser.map ChangeLanguage (s "change-language" </> string)
        ...
        ]

and we want to add language codes to all the urls in order to set the language like:

  • /en/about, /es/about, …
  • /en/login, /es/login, …

What is the recommended way for doing this?

Do we have to add to every line the parser?

Parser.map About (string </> s "about")

and add that code to every Route?

type Route
        = About lang

Or is there any better approach?

Thanks!

You can put the call to string before the entire parser:

routeWithLanguage : Parser (( String, Route ) -> a) a
routeWithLanguage =
  Parser.map Tuple.pair (string </> route)

Depending on your context, it might also be nice to use a custom type for supported languages instead of String. You can use use s and oneOf to accomplish that.

3 Likes

Thanks a lot @hkgumbs!

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.