C preprocessor as a template engine

Usage no npm install needed!

<script type="module">
  import cppt from 'https://cdn.skypack.dev/cppt';



status|proof of concept

Write templates in C preprocessor language.


./cppt -D'TITLE="cppt_demo_#1"' -D'USERS(u)=u("Jesus",2015)u("Alice",17)u("Max",-1)' <example/example.cppt

The output is a chunk of HTML:

<!doctype html>
<meta name="description" content="Example page">
<table class="users" id="my-table">

And here is what the template itself looks like:

#define html doctype t("html", "", head body)
#define doctype "<!doctype html>\n"

#define head t("head", "", title description "\n")
#define title "\n" t("title", "", TITLE)
#define description "\n" t1("meta",                                     \
                            a("name", "description")                    \
                            a("content", "Example page"))

#define body t("body", "", h1 table)
#define h1 "\n" t("h1", "", "Users:")
#define table "\n" t("table",                                           \
                     a("class", "users") a("id", "my-table"),           \
                     "\n" USERS(table_row)) "\n"
#define table_row(user, age) t("tr", "",                                \
                               t("td", "", user) t("td", "", #age)) "\n"

Preprocessor templates

Cppt template files must #define the html symbol as a string - the result of applying the template.

A few primitives are built in.

t(tag, attributes, content)

Creates a tag with given attributes and content.

t1(tag, attributes)

Creates a void (a.k.a. self-closing) tag with no content.

a(key, value)

Creates an attribute. Can be combined with other attributes to form the attributes string containing all of them.


Usage:  cppt [-D<definition>]... <TEMPLATE

Definitions have to be in exactly the same format as described in GCC(1).

Note: to pass a sequence of objects, you create a definition that accepts another macro, applies it to each object in a sequence and then concatenates the results. See the example.


  • GCC