Sunday, December 22, 2013

Best template lib for C

You've seen or heard about Clearsilver, CTPP, libctemplate. But the best template lib which has C spirit is libtemplate
Using templates in PHP and C++ has spoiled me. So when I started developing applications in C, I went hunting for a templating library that I could use again. I didn't find it, so after developing in a mixture of C for my lowlevel routines and C++ for my interface, I finally broke down and wrote a templating engine in C. (See Free HTML Template Engine.)
An example
#include "template.h"

int
main(void) {
    struct tpl_engine *engine;
    int n;
    char n1[10], n2[10], n3[10];
    engine = tpl_engine_new();

    /* Load the template file */
    tpl_file_load(engine, "test.tpl");

    for(n = 1; n <= 10; n++) {
        sprintf(n1, "%d", n);
        sprintf(n2, "%d", n*n);
        sprintf(n3, "%d", n*n*n);
        tpl_element_set(engine, "n", n1);
        tpl_element_set(engine, "n2", n2);
        tpl_element_set(engine, "n3", n3);

        /* Parse the template 'row' and add the result to element 'rows' */
        tpl_parse(engine, "row", "rows", 1);
    }

    tpl_parse(engine, "grid", "main", 0);
    printf("%s", tpl_element_get(engine, "main"));

    return 0;
}
test.tpl
<template name="grid">
<table>
<tr>
<th>n</th>
<th>nˆ2</th>
<th>nˆ3</th>
</tr>
{rows}
</table>
</template>
<template name="row">
<tr>
<td>{n}</td>
<td>{n2}</td>
<td>{n3}</td>
</tr>
</template> 

No comments:

Post a Comment