blob: 680f9a44ad1b1122a1f10612e39e3d85059103ce (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
# Simple Template Engine for C
The idea is stolen from [Tsoding](https://github.com/tsoding).
This is a template engine for the C programming language.
A really simple one, to be honset. To see how it works, it's best to just check
out examples, but in a nutshell: initially, everything is a string. After `%`
sign, it becomes C source code. basically, `%` sign acts as a flip-flop switch
between C and text. All of the text is wrapped inside the `OUT` macro, which
must be defined in the source code (name may be customized via command-line
arguments). To use the code, `#include generated.c` in the middle of function
where you need this template.
# Example
`main.c`:
```c
#define STRINGBUILDER_IMPLEMENTATION
#include "stringbuilder.h" /* refer to [c_headers](https://git.twistea.su/c_headers) */
#include <stdio.h>
int main(void) {
jac_sb sb = jac_sb_empty();
#define OUT(str) jac_sb_append_buf(&sb, str)
#define INT(i) jac_sb_snprintf(&sb, "%i", i); /* Note the semicolon */
#include "tmpl.c"
#undef OUT
printf("%s\n", sb.data);
jac_sb_free(sb);
return 727;
}
```
template file (`tmpl.c.ste`):
```html
<!DOCTYPE html>
<html>
<body>
%
for (int i = 0; i < 10; ++i) {
%<p>This is paragraph number % INT(i) %</p>%
}
%
</body>
</html>
```
Build: `cc ste.c -o ste && ste tmpl.c.ste && cc main.c -o main`
<!--vim:tw=80-->
|