Templating
Docraft includes a built-in template engine that replaces placeholders in the document tree with runtime values. This enables data-driven PDF generation from a single Craft Language template.
Variable Substitution
Register variables via DocraftTemplateEngine::add_template_variable() and
reference them with ${name} syntax:
<Text>Invoice for ${customer_name}</Text>
Registering Variables from JSON
DocraftTemplateEngine::add_template_variables_from_json() registers every field of
a JSON object as a template variable in one call, flattening nested objects into
dot-notation keys — this is what the docraft_tool --data <data.json> CLI flag uses
under the hood:
nlohmann::json data = {{"customer", {{"name", "Acme Corp"}}}, {"total", "€ 1,250.00"}};
engine->add_template_variables_from_json(data);
<Text>Invoice for ${customer.name} — ${total}</Text>
Strings are registered as-is; every other leaf value (numbers/bools/null/arrays) is
registered as its compact JSON text — e.g. an array field becomes a JSON array string
usable directly as a <Foreach model="${field}"> attribute. The JSON passed in must
be an object; a flattened key that collides with one already registered raises
TemplateVariableExistsException.
Foreach Loops
The <Foreach> element repeats its children for each item in a JSON
array. Inside the loop, use ${data("field")} to access item properties.
<Foreach model="${items}">
<Layout orientation="horizontal">
<Text weight="1">${data("name")}</Text>
<Text weight="1">${data("price")}</Text>
</Layout>
</Foreach>
Attribute |
Type |
Description |
|---|---|---|
|
string |
Template variable containing a JSON array. |
Image Data Injection
Raw RGB images can be injected at runtime and referenced in templates:
engine->add_image_data("chart", pixel_data, 400, 300);
// or from base64
engine->add_base64_image_data("chart", base64_string, 400, 300);
<Image data="chart" data_width="400" data_height="300"
width="200" height="150"/>
Templated Colors
Color attributes can also use template expressions:
<Text color="${status_color}">Status: ${status}</Text>
The template engine resolves the color at render time from the registered variable value (hex string or named color).