Static template generator for C
git clone git@soophie.de:/srv/git/ductape
Static template generator for C
ductape is static template generator with dynamic linking for C.
+---------+ (dlopen)
+---> | .so | ---------------------- load ------------------------+
+---------+ (ductape) | +---------+ |
| .html | --- compile ---+ v
+---------+ | +---------+ +----------+ (cc) +----------+
+---> | .h | --- include ---> | main.c | --- compile ---> | main |
+---------+ +----------+ +----------+
git clone git@soophie.de:/srv/git/ductape
cd ductape
sudo make install
Create a macro.h file which needs to define DUC_OUT for storing the handle the content is later written to and DUC_WRITE which handles consuming and writing onto the handle.
The file can be extended with custom macros (like STRING, NUMBER, MARKDOWN, etc.), to simplify writing more complex templates.
#define DUC_OUT ((str_t *) out) // cast custom handle
#define DUC_WRITE($str) { str_append(DUC_OUT, $str); } // define custom write function
#define STRING DUC_WRITE
The template example.html is defined (could be any kind of language), which includes the previously defined macro header file, followed by the start of the template definition DUC_TEMPLDEF with the first parameter being the UID and succeeding with varies parameters which allow for injecting dynamic data. The end of the template is marked with DUC_ENDTEMPL. Inside the template definition. the content is rendered, while content outside will be ignored.
The symbol % marks the delimiter between template and C code. In order to use the delimiter in the template it needs to be repeated twice to escape the character. All parameters passed into the template are bound to the ctx variable.
% #include "macro.h" %
% DUC_TEMPLDEF(
example,
char *message;
) %
<p>% STRING(ctx->message) %</p>
% DUC_ENDTEMPL %
The template can be compiled with the the installed CLI command ductape. Simply pass a list of files to the command and it will generate the corresponding .h (header) and .so (shared library) files based on the specified UID of the template.
ductape example.html
Finally, a main function can be defined which imports the compiled example.h header file, which contains everything needed to dynamically render the template, such as the example_t context structure passed into the template, as well as the example_render function which renders the template into the specified out handle.
#include "example.h"
int main(void) {
str_t out = STR_NULL;
example_t ctx = {
.message = "It works!",
};
int ret = example_render(&out, &ctx);
if (ret == 0) {
printf("%s", (char *) str_get(&out))
str_free(&out);
}
return ret;
}