evancz / url-parser和多个查询参数

时间:2017-03-30 07:21:02

标签: elm

我不确定如何访问多个查询参数。

source code中没有例子。

我知道如何使用<?>获取一个查询参数:

routeParser : Url.Parser (Route -> a) a
routeParser =
    Url.oneOf
        [ Url.map HomeRoute Url.top
        , Url.map SettingsRoute (Url.s "settings" <?> Url.stringParam "sortBy")
        ]


parseLocation : Location -> Route
parseLocation location =
    location
        |> Url.parsePath routeParser
        |> Maybe.withDefault NotFoundRoute

使用parsePath我可以使用查询参数获取Dict,但使用<?>是否有优雅的方式?

编辑:

我在elm-repl中使用了this example

> parsePath (s "blog" <?> stringParam "search" <?> stringParam "sortBy") (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "")
-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

The 1st argument to function `parsePath` is causing a mismatch.

5|   parsePath (s "blog" <?> stringParam "search" <?> stringParam "sortBy") (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "")
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Function `parsePath` is expecting the 1st argument to be:

    Parser (Maybe String -> Maybe String) (Maybe String)

But it is:

    Parser (Maybe String -> Maybe String -> Maybe String) (Maybe String)

Hint: It looks like a function needs 1 more argument.

1 个答案:

答案 0 :(得分:5)

您可以将<?>链接在一起以获取多个查询参数。让我们说你的SettingsRoute也期望一个pageNumber整数参数:

type Route
    = ...
    | SettingsRoute (Maybe String) (Maybe Int)

您的解析器可能如下所示:

Url.map SettingsRoute (Url.s "settings" <?> Url.stringParam "sortBy" <?> Url.intParam "pageNumber")

传入网址中的查询参数不需要与地图语句的顺序相同。以下示例将为上述路径提供相同的结果:

settings?sortBy=name&pageNumber=3
settings?pageNumber=3&sortBy=name

修改

您在REPL中添加了一个示例。您在REPL中遇到的问题是因为您没有正确映射到具有两个参数的内容。考虑REPL的这个例子:

> type alias SearchParams = { search : Maybe String, sortBy : Maybe String }
> parsePath (map SearchParams (s "blog" <?> stringParam "search" <?> stringParam "sortBy")) (Location "" "" "" "" "" "" "/blog" "?search=cats&sortBy=name" "" "" "")
Just { search = Just "cats", sortBy = Just "name" }
    : Maybe.Maybe Repl.SearchParams