Regis VidalRead between the cache lines

2026-10-21

tpl2c 1.0

tpl2c 1.0 is out. It is a templating engine for C: it translates a template, such as an HTML page, into a C function that writes the page. This site is built with it.

A template is text with three kinds of tag: <?c for C statements, <?= for a value, and <?h for declarations at file scope. A page that greets its reader:

<?c const char *who = hc_context; ?>
<p>Hello, <?= who ? who : "world" ?>!</p>

becomes this function, with tpl2c -o hello.c hello.chtml (shown without the #line directives that point the compiler back to the template):

void hc_template_hello(hc_out *hc_o, void *hc_context)
{
    const char *who = hc_context;
    hc_write(hc_o, "<p>Hello, ", 10);
    hc_put_str_esc(hc_o, HC_HTML, (who ? who : "world"));
    hc_write(hc_o, "!</p>\n", 6);
    (void)hc_o;
    (void)hc_context;
}

Every value is escaped for the template's language: HTML, CSS, JavaScript, JSON or a URL, chosen by the file's extension. A number takes a printf conversion, as in <?=%.2f price ?>, written by the runtime's own formatter, which is exact and needs no libm.

The translator reads each template once and writes the C as it goes, so it never holds a whole page in memory. The generated code and the runtime, hc.h and hc.c, are C89, build with -pedantic under GCC, Clang, TinyCC and Open Watcom, and allocate nothing: a page writes into a buffer you give it.

The source and the release are on GitHub, under the MIT license.