#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#include <ctype.h>
#include <template.h>
void
usage(void)
{
printf(
"libtemplate formatter usage\n"
"Usage:\n"
" tpl-formatter\n");
}
/*
* A custom formatter:
* - render json string in upper case.
*/
void
formatter_upper(struct json *json, struct writer *writer)
{
if (json_is_str(json)) {
char *value = json_get_value_str(json);
for (; *value != '\0'; value++) {
char c = (char) toupper(*value);
writer_write(writer, &c, 1);
}
}
}
int
main(int argc, char *argv[])
{
if (argc > 1 && strcmp(argv[1], "-h") == 0) {
usage();
return EXIT_SUCCESS;
}
/*
* Intantiate a new template,
* and register a custom formatter.
*/
struct template *tpl = template_new();
template_set_formatter(tpl, "upper", formatter_upper);
/*
* Template string to parse and render:
* - a variable using the html encoder formatter
* - a variable using the url encoder formatter
* - a variable using a custom formatter
*/
const char *tpl_string =
"html encoder formatter:\n"
" - before: {{html}}\n"
" - after : {{& html}}\n\n"
"url encoder formatter:\n"
" - before: {{url}}\n"
" - after : {{% url}}\n\n"
"custom (upper) formatter:\n"
" - before: {{word}}\n"
" - after : {{f:upper word}}\n\n";
/*
* Create a JSON object to feed the template
*/
struct json *json = json_obj_addv(NULL,
"html", json_str("<b>bob & son</b>"),
"url", json_str("http://foutaise.org"),
"word", json_str("foutaise"),
NULL);
/*
* Parse the string template,
* then render output using json data
*/
if (! template_parse_string(tpl, tpl_string))
errx(1, "%s", template_error_msg(tpl));
template_render(tpl, json);
/*
* Cleanup
*/
template_free(tpl);
json_free(json);
return EXIT_SUCCESS;
}