2 * Written by Richard W.M. Jones <rich@merjis.com>.
3 * Copyright (C) 2004 Merjis Ltd.
4 * $Id: cocanwiki_template.ml,v 1.4 2004/09/08 17:07:24 rich Exp $
6 * This module wraps around the Template library. It provides caching
7 * of templates and fills in standard fields on a host-specific basis.
17 try Sys.getenv "COCANWIKI_TEMPLATES"
18 with Not_found -> "/usr/share/cocanwiki/templates" in
20 try (Unix.stat path).Unix.st_kind = Unix.S_DIR
21 with Unix.Unix_error _ -> false in
22 if not (is_dir base) then
23 failwith ("environment variable $COCANWIKI_TEMPLATES " ^
24 "must be set to point to my 'templates' directory " ^
25 "(see README file for more details)");
28 (* The webserver gets restarted regularly enough that this is reasonable. *)
29 let { tm_year = year } = gmtime (time ())
30 let year = year + 1900
32 (* Cache of precompiled templates, arranged by full path. *)
33 let cache = Hashtbl.create 32
35 let _get_template filename =
36 let path = base // filename in
37 let stat = Unix.stat path in
38 let mtime = stat.st_mtime in
41 let template, old_mtime = Hashtbl.find cache path in
42 if old_mtime < mtime then (
43 (* The template has changed on disk since it was compiled. Reload. *)
44 let template = Template.template path in
45 Hashtbl.replace cache path (template, mtime);
51 (* Template not seen before, so load it. *)
52 let template = Template.template path in
53 Hashtbl.replace cache path (template, mtime);
56 let get_template (dbh : Dbi.connection) hostid filename =
57 let template = _get_template filename in
59 (* Get standard fields concerning this host from the database. *)
60 let sth = dbh#prepare_cached "select theme_css from hosts
62 sth#execute [`Int hostid];
65 match sth#fetch1 () with
66 [ `Null ] -> "/_css/standard.css"
67 | [ `String file ] -> file
68 | _ -> assert false in
70 template#set "theme_css" theme_css;
73 let sth = dbh#prepare_cached "select url, label, ordering from sitemenu
74 where hostid = ? order by ordering" in
75 sth#execute [`Int hostid];
77 let table = sth#map (function [`String url; `String label; _] ->
78 [ "url", Template.VarString url;
79 "label", Template.VarString label ]
80 | _ -> assert false) in
82 template#table "sitemenu" table;
85 template#set "cocanwiki_package" Cocanwiki_version.package;
86 template#set "cocanwiki_version" Cocanwiki_version.version;
89 template#set "year" (string_of_int year);