Ocsigen by example, Part 4: suffix parameters
In the examples we've seen so far, GET parameters were passed using the standard scheme (RFC 3986), ie, an ampersand delimited list of key-value assignments. As an alternative, Eliom offers also the possibility of encoding parameters as slash-delimited suffixes to the main URL. For many applications this produces friendlier and cleaner looking URLs.
As an example, consider a service "foobar" taking three integers as parameter: "year", "month", and "day". In the standard scheme, the service could be invoked with today's date by calling "foobar?year=2009&month=3&day=17". Using the suffix scheme, the same invocation becomes "foobar/2009/3/17". You trade the flexibility of specifying parameters by any order for the improved legibility.
The code sample below shows the definition of the service "foobar" using suffix parameters. Note that only the declaration of the service needs to change; any links towards this service created with Eliom_predefmod.Xhtml.a will automatically reflect the new convention (yet another reason to always use Eliom_predefmod.Xhtml.a!).
(************************************************************************)
(* Example for suffix parameters. *)
(************************************************************************)
open XHTML.M
open Eliom_parameters
(************************************************************************)
(* The "foobar" service takes three GET parameters, all integers.
It illustrates the use of Eliom_parameters.suffix to construct
friendlier looking URLs.
*)
let foobar_handler _ (year, (month, day)) () =
let date = (string_of_int year) ^ "/" ^ (string_of_int month) ^ "/" ^ (string_of_int day)
in Lwt.return
(html
(head (title (pcdata "Foobar")) [])
(body [p [pcdata ("The date specified by the GET parameters is " ^ date)]]))
let foobar_service =
Eliom_predefmod.Xhtml.register_new_service
~path: ["foobar"]
~get_params: (Eliom_parameters.suffix
(Eliom_parameters.int "year" **
(Eliom_parameters.int "month" **
Eliom_parameters.int "day")))
foobar_handler
(************************************************************************)
(* The "main" service just provides a link to the "foobar" service.
*)
let main_handler sp () () =
Lwt.return
(html
(head (title (pcdata "Main")) [])
(body [p [Eliom_predefmod.Xhtml.a foobar_service sp [pcdata "Click for foobar"] (2009, (3, 17))]]))
let main_service =
Eliom_predefmod.Xhtml.register_new_service
~path: [""]
~get_params: Eliom_parameters.unit
main_handler

Very interesting blog entry! I did not know that it was possible to use typed parameters with suffixes.
Yours,
d.
Reply to this