htmlcc
htmlcc is a simple HTML templating engine for C. At compile time, htmlcc transpiles template files into C functions to generate HTML, i.e. templates are statically compiled into C.
Usage
python -m htmlcc input.html > output.c
By default, htmlcc emits C code which prints the generated HTML to standard output. An extensible framework is provided to customise this behaviour via the --emitter
flag (see htmlcc/emitter/cgit.py for an example implementation).
Features
htmlcc syntax is based loosely on Jinja, using double curly braces.
The following language features are supported:
{% page page_name %} ... {% endpage %}
declares a page function with the C signaturevoid page_name(void) { ... }
.- Page functions can declare arguments using the syntax
{% page page_name(char *arg1, int arg2) %}
, etc. {% block block_name %} ... {% endblock %}
is equivalent, but emitters may override this and provide for different behaviour.
- Page functions can declare arguments using the syntax
{{ expression }}
escapes and outputs the givenchar*
expression as HTML text.{{ expression|attr }}
escapes and outputs the givenchar*
expression as an HTML attribute.{{ expression|urlencode }}
escapes and outputs the givenchar*
expression as a percent-encoded URL component (not implemented for the stdout emitter).{{ expression|%d }}
,{{ expression|%ld }}
escape and output the givenint
andlong
expressions respectively.
{% if expr %} ... {% endif %}
,{% while expr %} ... {% endwhile %}
,{% for init_expr; cond_expr; loop_expr } ... {% endfor %}
generate if/while/for statements respectively.{% if expr %} ... {% elif expr %} ... {% else %} ... {% endif %}
blocks are supported.
{! ... !}
inserts raw C code, e.g.{! foo.bar(); !}
.{# ... #}
is a comment, which is not included in the generated template.
Using the default emitter, generated C code is cross-platform, has no dependencies, and requires no memory allocations.
Example
{! char *my_name = "Alice"; !}
{% page hello_world %}
<html>
<body>Hello world, my name is {{ my_name }}!</body>
</html>
{% endpage %}
The above template transpiles into the following C code:
#include <stdio.h>
void output_variable_as_text(char *variable) { /* escape special characters ... */ }
char *my_name = "Alice";
void hello_world(void) {
printf("%s", "<html>\n");
printf("%s", " <body>Hello world, my name is ");
output_variable_as_text(my_name);
printf("%s", "!</body>\n");
printf("%s", "</html>\n");
}
See examples/helloworld.html for a more complex example making use of variables and control flow.