'How to generate URL from a route in Opium

Consider the following Opium web application that has two routes: / and /greetings/:name/:flowers. In /, there is a navigation bar that links to a URL handled by the other route (e.g. /greetings/foobar/99). The problem is: how do I generate the URL for that other route without manually hardcoding its URL? If possible, I also want to avoid the use of string concatenation for building URLs.

In other words, I am looking for something similar to Ruby on Rails' ActionView::Helpers::UrlHelper#link_to or Django's django.urls.reverse(), which are able to generate URLs from routes.

open Opium

let index_handler _req =
  let open Tyxml.Html in
  html
    (head (title (txt "Index")) [])
    (body [nav [ul [
        li [a ~a:[a_href "/"] [txt "Index"]];
        (* ATTENTION. How do I avoid hardcoding the following URL? *)
        li [a ~a:[a_href "/greetings/foobar/99"] [txt "Greetings"]]; 
    ]]])
  |> Response.of_html
  |> Lwt.return

let greetings_handler req =
  let name = Router.param req "name" in
  let flowers = Router.param req "flowers" in
  "Hello, " ^ name ^ "!\n" ^
  "You get " ^ flowers ^ " flowers."
  |> Response.of_plain_text
  |> Lwt.return

let _ =
  App.empty
  |> App.get "/" index_handler
  |> App.get "/greetings/:name/:flowers" greetings_handler
  |> App.run_command

OCaml version: 4.08.1; Opium version: 0.20.0.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source