Templating Engines

Example usage of HTML templating engines with naboris.

# Basics

At the end of the day templating engines are just functions which return a string. This makes it much easier to create dynamic HTML documents generated by your server. There can be many implementations of this but usually you will define a template and use some data structure to augment that template. The result of all of this will be a partial or complete document which then you can server to the user.

Some libraries for templating:

# Full Example

Here is a very small example of a requestHandler using Mustache to create a dynamic HTML document

1let template = Mustache.of_string("<!doctype html>
2<html>
3  <title>{{pageName}}</title>
4</html>
5<body>
6  <h2>Welcome to {{pageName}} page</h2>
7</body>
8</html>");
9
10let startServer = () => {
11  let port = 9000;
12  let serverConfig = Naboris.ServerConfig.create()
13    |> Naboris.ServerConfig.setRequestHandler((route, req, res) =>
14        switch (Naboris.Route.meth(route), Naboris.Route.path(route)) {
15          | (GET, [pageName]) =>
16            let json = `O([("pageName", `String(pageName))]);
17            let html = Mustache.render(template, json);
18            Naboris.Res.status(200, res)
19              |> Naboris.Res.html(req, html);
20          | _ =>
21            Naboris.Res.status(404, res)
22              |> Naboris.Res.text(req, "Not Found.");
23        });
24
25  Naboris.listenAndWaitForever(port, serverConfig);
26}
27
28Lwt_main.run(startServer());
1let template = Mustache.of_string "<!doctype html>\
2<html>\
3  <title>{{page_name}}</title>\
4</html>\
5<body>\
6  <h2>Welcome to {{page_name}} page</h2>\
7</body>\
8</html>"
9
10let start_server ()=
11  let port = 9000 in
12  let server_config = Naboris.ServerConfig.create()
13    |> Naboris.ServerConfig.setRequestHandler(fun route req res ->
14      match (Naboris.Route.meth route, Naboris.Route.path route) with
15        | (GET, [page_name]) ->
16          let json = `O [ ("page_name", `String page_name) ] in
17          let html = Mustache.render template json in
18          Naboris.Res.status 200 res
19            |> Naboris.Res.html req html
20        | _ ->
21          Naboris.Res.status 404 res
22            |> Naboris.Res.text req "Not Found.") in
23
24  Naboris.listenAndWaitForever port server_config
25
26let _ = Lwt_main.run(start_server ())

Visiting http://localhost:9000/:pageName will render an html document with the parameter from the path.

Support us on GitHub

Star, follow, fork

Star Fork

Found a typo? a bug? or something that just doesn't make any sense? Help improve these docs by opening a github issue.

naboris source code is licensed MIT.
It can be used, copied, and modified free of charge. However, the software is provided "as is" without any warranties. Click the link above for more information.