Examples

Writing a forum

As an example, we will now write a small forum. Our forum has a main page, summarising all the messages and a page for each message. All the functions to access the database and print the result are left to the reader. We only want to show the structure of the site. Suppose you have written a function news_headers_list_box that writes the beginning of messages, and message_box that write a full message.

(* All the services: *)

let main_page = service ~path:[""]
    ~get_params:unit ()

let news_page = service ["msg"] (int "num") ()

(* Construction of pages *)

let home () () =
  page
    [h1 [pcdata "Mon site"];
     news_headers_list_box
       anonymoususer news_page]

let print_news_page i () =
  page
    [h1 [pcdata "Info"];
     message_box i anonymoususer]

(* Services registration *)

let _ = register
  ~service:main_page
  home

let _ = register
  ~service:news_page
  print_news_page

Now the same example with a login box on each page. We now have two versions of each page: connected and not connected. We need two actions (for connection and disconnection). Suppose we have the functions login_box, connected_box, and connect.

(* All the services: *)

let main_page = service ~path:[""] ~get_params:unit ()

let news_page = service ["msg"] (int "num") ()

let connect_action =
  post_coservice'
    ~post_params:(string "login" ** string "password")

(* Construction of pages *)

let home () () =
   match get_volatile_data ~table:my_table () with
   | Eliom_state.Data_session_expired
   | Eliom_state.No_data ->
     page
       [h1 [pcdata "My site"];
        login_box connect_action;
        news_headers_list_box anonymoususer news_page]
   | Eliom_state.Data user ->
      page
        [h1 [pcdata "Mon site"];
         text_box "Bonjour !";
         connected_box user disconnect_action;
         news_headers_list_box user news_page]

let print_news_page i () =
   match get_volatile_data ~table:my_table () with
   | Eliom_state.Data_session_expired
   | Eliom_state.No_data ->
      page
        [h1 [pcdata "Info"];
         login_box connect_action;
         message_box i anonymoususer]
   | Eliom_state.Data user ->
      page
        [h1 [pcdata "Info"];
         connected_box user disconnect_action;
         message_box i user]

(* Services registration *)

let _ = register
  ~service:main_page
  home

let _ = register
  ~service:news_page
  print_news_page

let launch_session user =
  set_volatile_data my_table user

let _ = Eliom_output.Action.register
  ~action:connect_action
    (fun h (login, password) ->
      launch_session (connect login password); return [])

Miniwiki

Ocsigen's source code contains an example of Wiki written with Eliom by Janne Hellsten. It is called Miniwiki.