Static template generator for C
git clone git://soophie.de/ductape
8
install: build9
cp ctl /usr/local/bin/10
cp libctl.h /usr/local/include/11
rm ./ctl13
clean:
1
# ctl3
Static template generator for C5
## Usage7
```html8
<h1>Hello, % STRING(name) %!</h1>9
<ul>10
% for (int i = 0; i < len; i++) { %11
<li>Item % NUMBER(i) %</li>12
% } %13
</ul>14
```16
```bash17
ctl example.html > ctl_example.h18
```20
```c21
#define LIB_CTL_IMPL22
#include <libctl.h>24
#define CTL_OUT(out, x) { \25
str_append(out, x); \26
}27
#define STRING(x) str_append(ctl_out, x);28
#define NUMBER(x) { \29
str_appendf(ctl_out, "%d", x); \30
}32
void ctl_fn_example(char **ctl_out, ctl_ctx_t ctx) {33
(void) ctx;34
char *name = "world";35
int len = 10;36
#include "ctl_example.h"37
}38
```
1
#ifndef LIB_CTL_H2
#define LIB_CTL_H4
#include <libhttp.h>5
#include <libstr.h>7
typedef struct ctl_ctx ctl_ctx_t;8
typedef void (*ctl_fn_t)(char **ctl_out, ctl_ctx_t ctx);10
struct ctl_ctx {11
http_request_t *request;12
char *title;13
ctl_fn_t fn;14
};16
void ctl_init(ctl_fn_t fn);17
http_response_t ctl_serve_page(http_request_t *request, const char *title, ctl_fn_t fn);18
http_response_t ctl_serve_component(http_request_t *request, ctl_fn_t fn);20
#ifdef LIB_CTL_IMPL22
static ctl_fn_t ctl_fn = NULL;24
void ctl_init(ctl_fn_t fn) {25
ctl_fn = fn;26
}28
http_response_t ctl_serve_page(http_request_t *request, const char *title, ctl_fn_t fn) {29
char *html = NULL;30
ctl_ctx_t ctx = {31
.request = request,32
.title = title,33
.fn = fn,34
};35
ctl_fn(&html, ctx);36
http_response_t response = http_response_create(HTTP_STATUS_OK);37
http_header_set(&response, "Content-Type", "text/html");38
http_response_body(&response, html, strlen(html));39
free(html);40
return response;41
}43
http_response_t ctl_serve_component(http_request_t *request, ctl_fn_t fn) {44
char *html = NULL;45
ctl_ctx_t ctx = {46
.request = request,47
};48
fn(&html, ctx);49
http_response_t response = http_response_create(HTTP_STATUS_OK);50
http_header_set(&response, "Content-Type", "text/html");51
http_response_body(&response, html, strlen(html));52
free(html);53
return response;54
}56
#endif /* LIB_CTL_IMPL */57
#endif /* LIB_CTL_H */