Skip to content

HTML pages and templates

A page is a string. Returns.html answers it at 200 as text/html; charset=utf-8; Response.html does the same under any status. Spindle has no template language: render with whichever library you like. Escaping what a person sent is the renderer’s job, and each of these escapes text unless told not to.

Renderer How you write a page Turning a page into a string
htmlit combinators, no dependencies Htmlit.El.to_string ~doctype:true page
TyXML combinators, or HTML through tyxml-ppx, checked against the standard as it compiles Format.asprintf "%a" (Tyxml.Html.pp ()) page
html_of_jsx JSX, in the mlx dialect "<!doctype html>" ^ JSX.render page
jingoo Jinja templates, in files Jingoo.Jg_template.Loaded.eval template ~models

Each program serves the same page at /hello/{name}:

(* A page made with htmlit: combinators, and no dependency of their own.
Spindle has no template language: [Returns.html] answers the string a
renderer made, so any renderer fits, and escaping what a person sent is
the renderer's -- [El.txt] escapes, so the <b>kim</b> of
/hello/%3Cb%3Ekim%3C%2Fb%3E is words on the page. *)
open Spindle.Syntax
module El = Htmlit.El
let name = Spindle.Path.string "name"
let greeting name =
El.page ~lang:"en" ~title:"Hello"
(El.body [ El.h1 [ El.txt ("Hello, " ^ name ^ "!") ] ])
let routes =
[
Spindle.get
Spindle.Path.(s "hello" / name)
Spindle.Returns.html
(let+ name = Spindle.param name in
Ok (El.to_string ~doctype:true (greeting name)));
]
let () =
Spindle.Log.setup ();
Eio_main.run @@ fun env -> Spindle.serve env routes
Terminal window
$ curl localhost:8080/hello/kim
<!DOCTYPE html>
<html lang="en"><head>...<title>Hello</title></head><body><h1>Hello, kim!</h1></body></html>

A name with markup in it is escaped: visit /hello/<b>kim</b> and the page reads Hello, <b>kim</b>!, tags and all, rather than a bold name.

A refusal is still JSON, on a page’s route as on any other. For an HTML page when no route matches, pass your own answer as ~not_found (How routes are matched). To read a form a page posts, see Forms and file uploads; a form posted from another site is refused by the cross-site check.