ECaml — a simple template engine for OCaml

ECaml logo



% ecaml --help
ecaml - a simple template tool for OCaml
Usage: ecaml [OPTIONS] template.eml
  -o FILE destination file to output an OCaml code; default is
  -p STR  printer function to apply to strings; default is print_string
  -esc-p STR  function to apply to <%= %> parts but not to <%=raw %>; default is the same as -p
  -d    write a directive with original file name for more impressive error messages
  -header STR header to write before the output
  -footer STR footer to write after the output
  -help  Display this list of options
  --help  Display this list of options


This tool is so stupid, so don't forget about ; at the end of your expressions!

I don't want to add any other features yet, because I want to keep this tool simple.


komar@thinkpad /home/komar/devel/ecaml % cat test.eml

<p><%= if Sys.os_type = "Unix" then "Hello world!" else "gtfo" %></p>
% List.iter (fun s ->
<li><%= s %></li>
% ) ["hello"; "from"; "list"];

komar@thinkpad /home/komar/devel/ecaml % ./ecaml test.eml
komar@thinkpad /home/komar/devel/ecaml % cat

print_string "<html>\n";
print_string "<head></head>\n";
print_string "<body>\n";
print_string "<p>";print_string ( if Sys.os_type = "Unix" then "Hello world!" else "gtfo" );print_string "</p>\n";
print_string "<ul>";
 List.iter (fun s ->
print_string "<li>";print_string ( s );print_string "</li>";
 ) ["hello"; "from"; "list"];
print_string "</ul>\n";
print_string "</body>\n";
print_string "</html>\n";

komar@thinkpad /home/komar/devel/ecaml % ocaml

<p>Hello world!</p>

And how to use this stuff with ocsigen?

Write something like:

% let f buf ~title ~content = (
<html xmlns="">
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
    <title><%= title %></title>
    <p><%= content %></p>
% )

Then compile this template with -p 'Buffer.add_string buf':

komar@thinkpad /home/komar % ~/devel/ecaml/ecaml -p 'Buffer.add_string buf' site_template.eml
komar@thinkpad /home/komar % cat

 let f buf ~title ~content = (
Buffer.add_string buf "<html xmlns=\"\">\n";
Buffer.add_string buf "  <head>\n";
Buffer.add_string buf "    <meta content=\"text/html; charset=UTF-8\" http-equiv=\"Content-Type\" />\n";
Buffer.add_string buf "    <title>";Buffer.add_string buf ( title );Buffer.add_string buf "</title>\n";
Buffer.add_string buf "  </head>\n";
Buffer.add_string buf "  <body>\n";
Buffer.add_string buf "    <p>";Buffer.add_string buf ( content );Buffer.add_string buf "</p>\n";
Buffer.add_string buf "  </body>\n";
Buffer.add_string buf "</html>";

And now you can get the output with:

let title = "hi" in
let content = "nothing to do there" in
let buf = Buffer.create 666 in
Site_template.f buf ~title ~content;
Buffer.contents buf

See also