ELM get query parameter as string

落爺英雄遲暮 提交于 2020-06-28 03:21:37

问题


Based on this post and thanks to the @glennsl iam getting some where.

First if someone has a link that i could learn about the parses i will be very glad.

page : Url.Url -> String
page url = 
  case (Parser.parse (Parser.query (Query.string "name")) url) of
    Nothing -> "My query string: " ++ (Maybe.withDefault "empty" url.query)
    Just v -> case v of
      Just v2 -> "Finnaly a name"
      Nothing -> "????"

As far i can understand the expression Parser.parse (Parser.query (Query.string "name")) urlis returning a Maybe (Maybe String) I see this as the parser could return something, and if do it could be an string, is that right?

In my mind if i have the parameter name in my url then my first Just would be executed and then i can get the name.

But no mather what i put on my url it always go the the first Nothing

The result i got


回答1:


The problem is that you're not parsing the path part of the URL, which is what Url.Parser is primarily for. You have to match the path exactly.

Here's a parser that will match your URL:

s "src" </> s "Main.elm" <?> (Query.string "name")

Note also that parsing the query string is optional, meaning this will also match your URL:

s "src" </> s "Main.elm"

But as long as you include a query param parser, that also has to match.

If all you care about is the query parameter, you'll have to parse the query string specifically, by either writing your own function to do so, or using a library like qs for example:

QS.parse
    QS.config
    "?a=1&b=x"

== Dict.fromList
    [ ( "a", One <| Number 1 )
    , ( "b", One <| Str "x" ) 
    ]


来源:https://stackoverflow.com/questions/62264254/elm-get-query-parameter-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!