#import "Basic";
html_template :: #import "htmltemplate";
/**
jai 02_with_comments.jai -quiet && ./02_with_comments
*/
/** Below is a template. This would you read from a file normally, but
this is up to you. */
YOUR_TEMPLATE_FILE :: #string STR_END
{{ :page_title: }}
{{ :article_title: % % }}
This demonstrates a {{ :example1: % % }}
{{ :example2: This demonstrates % % }}
{{ :example3: Or %1 numbered %2 that can be reused: %1 }}
Lets demonstrate looping!
{{ loop:example4: - %1 %3
}}
STR_END;
main :: () {
using html_template;
/** Now lets create some data, so we can populate the placeholders with it.
For that, we need an dynamic array, which stores our data: */
queue_action: [..]Action;
/** If you keep this exact name you don't have to pass it later to the
`commit()` proc, since one of its overloads is a macro.
But you can always chose a different name for your array and pass
it directly to the `commit()` proc if you want.
Now lets create the data for the placeholders: */
commit(
id = "page_title",
value = "Example 01",
);
commit(
id = "bg_color",
value = "#323240",
);
commit(
id = "font_color",
value = "#DFDFFF",
);
// You can pass multiple values as static array
commit(
id = "article_title",
value = .[ "Example", "01" ],
);
// Or via variadic procs
commit("example1", "simple", "replacement");
commit("example2",
"#some_path",
"_self",
"positional",
"placeholders"
);
commit("example3",
"even",
"placeholders"
);
// This identifier `example4` is a loop. The amount of iterations
// is defined by the amount of sub-arrays:
commit("example4", .[
.[ "articles", "target=\"_self\"", "to read" ],
.[ "about", "target=\"_self\"", "me" ],
.[ "books", "target=\"_self\"", "" ],
.[ "extern", "", "website" ],
]);
/** Now we can generate the html file.
We have to declare if the template if from a raw string or file(path).
In this case we're reading the template from a string, so we pass `.STRING`.
If you omit the very last parameter, like in this case, it does not write
the generated content into a file.
*/
success, // If something went wrong, it's indicated here.
html_string, // Your output as string. (You have to free it).
exit_code, // More needed for debugging, consult the `lib.jai` for more information.
error_message // This returns the exact error message if !success. (You have to free it)
:= generate(queue_action, YOUR_TEMPLATE_FILE, .STRING);
defer {
free(html_string);
free(error_message);
}
if !success {
log_error(error_message);
return;
}
log("%", html_string);
#if false {
#import "File";
write_entire_file("01_example.html", html_string);
}
/** If you want to know, what happens if you supply wrong paramaters,
visit `test/test.jai`. It contains several test cases with brief
explainations. */
}