Created
November 3, 2016 02:18
-
-
Save lpereira/1d52f21d0751382db8dbc441196dc4b7 to your computer and use it in GitHub Desktop.
Lwan template with arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <lwan.h> | |
#include <lwan-template.h> | |
#include <strbuf.h> | |
struct thing { | |
lwan_tpl_list_generator_t generator; | |
const char *name; | |
}; | |
struct foobar { | |
int banana; | |
struct thing thing; | |
struct thing things[16]; | |
}; | |
static int | |
thing_generator(coro_t *coro) | |
{ | |
struct foobar *foobar = coro_get_data(coro); | |
int i; | |
for (i = 0; i < 16; i++) { | |
foobar->thing.name = foobar->things[i].name; | |
if (!foobar->thing.name) | |
break; | |
if (coro_yield(coro, 1)) | |
break; | |
} | |
return 0; | |
} | |
int main(void) | |
{ | |
lwan_var_descriptor_t desc[] = { | |
TPL_VAR_INT(struct foobar, banana), | |
TPL_VAR_SEQUENCE(struct foobar, thing, thing_generator, ( | |
(const lwan_var_descriptor_t[]) { | |
TPL_VAR_STR(struct foobar, thing.name), | |
TPL_VAR_SENTINEL | |
} | |
)), | |
TPL_VAR_SENTINEL | |
}; | |
lwan_tpl_t *tpl = lwan_tpl_compile_string("banana:{{banana}}\n" | |
"{{#thing}}- {{thing.name}}\n" | |
"{{/thing}}", desc); | |
if (!tpl) return 1; | |
strbuf_t *applied = lwan_tpl_apply(tpl, &(struct foobar) { | |
.banana = 47, | |
.things[0] = { .name = "foo" }, | |
.things[1] = { .name = "bar" }, | |
.things[2] = { .name = "baz" }, | |
.things[3] = { .name = NULL }, | |
}); | |
printf("applied template:\n\n%s\n\n", strbuf_get_buffer(applied)); | |
strbuf_free(applied); | |
lwan_tpl_free(tpl); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment