Skip to content

Guide · Developer

PDF template variables: binding JSON data to HTML templates

Bind JSON data to HTML or saved PDF templates: placeholders, each loops, if/else and unless conditional sections, escaping, missing values and a schema.

Updated 17 min readSublimePDF Team

Template variables separate what a document looks like from what it says. You write the layout once as HTML and CSS, with placeholders where values go, and send a JSON object with the values on every call. The API gives you two equal ways to do that:

  • Send the HTML with the data to POST /html-to-pdf as { "html": "...", "data": { ... } }. The layout lives in your code or repository and ships with it.
  • Save the HTML as a template in the app and send only the data to POST /templates/{id}/generate as { "data": { ... } }. The layout can be changed in the app without a deploy, and each call carries only data.

The placeholders, loops and conditionals in this guide work the same way in both. To try them, download the sample template.html and data.json into one folder, set SUBLIMEPDF_API_KEY, and run this with Node.js 18 or later (save it as render-invoice.mjs). It sends the HTML with the data, or, if SUBLIMEPDF_TEMPLATE_ID is set, the data alone to your saved copy of the template:

import { readFile, writeFile } from "node:fs/promises";
 
const apiBase = process.env.SUBLIMEPDF_API_BASE_URL ?? "https://api.sublimepdf.com/v1";
const apiKey = process.env.SUBLIMEPDF_API_KEY;
if (!apiKey) throw new Error("Set SUBLIMEPDF_API_KEY");
 
const data = JSON.parse(await readFile("data.json", "utf8")); // { seller, customer, invoice, items, totals, payment, notes }
const templateId = process.env.SUBLIMEPDF_TEMPLATE_ID;
 
const [path, body] = templateId
  ? [`/templates/${encodeURIComponent(templateId)}/generate`, { data }]
  : ["/html-to-pdf", { html: await readFile("template.html", "utf8"), data }];
 
const res = await fetch(apiBase + path, {
  method: "POST",
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
  body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`SublimePDF ${res.status}: ${await res.text()}`);
await writeFile("invoice.pdf", Buffer.from(await res.arrayBuffer()));
console.log("Saved invoice.pdf");

The same two requests with curl and jq, which wraps the file contents in the request body:

# HTML with data
jq -n --rawfile html template.html --slurpfile data data.json '{html: $html, data: $data[0]}' |
  curl -s https://api.sublimepdf.com/v1/html-to-pdf \
    -H "Authorization: Bearer $SUBLIMEPDF_API_KEY" -H "Content-Type: application/json" \
    -d @- -o invoice.pdf
 
# Saved template ID with data
jq -n --slurpfile data data.json '{data: $data[0]}' |
  curl -s "https://api.sublimepdf.com/v1/templates/$SUBLIMEPDF_TEMPLATE_ID/generate" \
    -H "Authorization: Bearer $SUBLIMEPDF_API_KEY" -H "Content-Type: application/json" \
    -d @- -o invoice.pdf

This guide is about that data object and the placeholders that consume it: nested paths, loops for line items, conditional sections, escaping, what happens when a value is missing, and how to shape a payload that an agent can fill reliably.

The contract: templates lay out, callers compute

One rule shapes everything else. A template places values on the page. It does not calculate totals, apply tax, convert currencies or format dates. Your code does that before the call and sends display-ready values. The sample invoice data shows the result: amounts arrive as "€2,400.00", dates as "22 Nov 2026", and the notes field says so explicitly.

This keeps the arithmetic in one place, where you can test it, and means the PDF always shows exactly the numbers your system recorded.

Placeholders and nested paths

A placeholder is a path into the data object, written in double braces. Dots walk into nested objects:

Bill to: {{customer.name}}, {{customer.address.city}}
{ "customer": { "name": "Example GmbH", "address": { "city": "Berlin" } } }

Output: Bill to: Example GmbH, Berlin

Group related fields into objects (seller, customer, invoice, totals) rather than using long flat names such as customerAddressCity. Templates read better, and an agent filling the payload sees which fields belong together.

Loops: line items with each

{{#each}} repeats a block once per array element. Inside the block, paths are relative to the current item, and Handlebars provides @index (zero-based), @first and @last. An {{else}} block renders when the array is empty:

{{#each items}}{{@index}}. {{description}} {{amount}}{{#if @last}} (last){{/if}}
{{else}}No items
{{/each}}
DataOutput
items with two entries0. Design €2,400.00 then 1. Support €600.00 (last)
"items": []No items

Two more patterns from the invoice template:

  • Arrays of strings use {{this}}. The address is ["14 Example Street", "London EC1A 1AA"] and the template writes {{#each address}}{{this}}<br>{{/each}}. Sending lines as an array keeps markup out of your data (see escaping below).
  • Parent values inside a loop use ../. With {{#each items}}{{description}} ({{../invoice.currency}}){{/each}} each line can print the invoice currency, giving Design (EUR).

Loops pair with print CSS. The sample invoice repeats its table header on every page and keeps rows from splitting; the long invoice runs 60 lines over 4 pages. The HTML to PDF CSS guide covers that side.

Conditional content: if, else and unless

Conditional sections let one template cover several versions of a document: a paid and an unpaid invoice, a statement with and without an overdue notice, a report with an optional appendix. Handlebars provides two block helpers for this.

{{#if}} renders its block when the value is truthy, otherwise the optional {{else}} block. {{#unless}} is the inverse: its block renders when the value is falsy.

{{#if invoice.purchaseOrder}}PO {{invoice.purchaseOrder}}{{else}}No PO{{/if}}
{{#unless invoice.paid}}Payment due {{invoice.dueDate}}{{else}}Thank you for your payment{{/unless}}

With "invoice": { "paid": false, "dueDate": "22 Dec 2026" } the second line printed Payment due 22 Dec 2026, and with "paid": true it printed Thank you for your payment.

Whole sections, not just words

A conditional block can hold any amount of HTML, so it is also how you include or leave out entire sections:

{{#if reverseCharge}}
  <section class="vat-note">
    <h2>Reverse charge</h2>
    <p>{{reverseCharge.text}}</p>
  </section>
{{/if}}
 
{{#if appendix}}
  <section class="appendix" style="break-before: page">
    <h2>Appendix</h2>
    {{#each appendix}}<p>{{this}}</p>{{/each}}
  </section>
{{/if}}

Send the object or array when the section applies, and leave it out, or send null or an empty array, when it does not. A section that starts a new page, like the appendix above, only adds that page when it is rendered.

Several branches: else if

Handlebars' block helper guide says conditionals "may also be chained by including the subsequent helper call within the else mustache". That gives you else if for a status with more than two outcomes:

{{#if invoice.paid}}<span class="badge">Paid</span>
{{else if invoice.overdue}}<span class="badge badge-red">Overdue</span>
{{else}}<span class="badge">Due {{invoice.dueDate}}</span>{{/if}}

We ran it with the three combinations of paid and overdue and got Paid, Overdue and Due 22 Dec 2026 in turn.

No comparisons inside the template

{{#if}} tests one value for truthiness. It cannot compare: {{#if (eq invoice.status "Paid")}} failed with "eq" not defined, because Handlebars has no built-in eq helper and the documentation lists no comparison helpers. The API supports only the built-in helpers (if, unless, each, with, lookup, log) and rejects any other helper, partial or decorator with 422 validation_error (code template_unknown_helper or template_unsupported) naming it and its line. A saved template is checked when you save it, so the mistake shows up then rather than at render time. Decide in your code and send the result as a flag, such as "paid": true or "overdue": false. That keeps the business rule (when is an invoice overdue?) in code you can test, and the template only reacts to it.

What counts as true

Handlebars treats false, undefined, null, "", 0 and [] as false, which is not quite JavaScript's idea of truthy. We ran {{#if v}}shown{{else}}hidden{{/if}} with each value:

vResult
0hidden
"0"shown
""hidden
false, nullhidden
[] (empty array)hidden
{} (empty object)shown

The first row catches people out. A discount of 0 or a quantity of 0 hides the block. Handlebars has an includeZero=true option on if, which showed the block for 0 in our run, but a simpler rule avoids the question: send display values as strings ("0", "€0.00"), and use booleans only for genuine yes/no decisions such as paid.

Missing values and strict mode

What happens when a field the template uses is not in the data depends on whether the template is compiled in strict mode. Handlebars' documentation describes strict mode as throwing "rather than silently ignore missing fields". In default mode a missing value prints as an empty string, which is how blank customer names end up on real invoices. The repository renders its samples in strict mode, and these are the results:

TemplateDataStrict mode result
{{customer.name}}{ "customer": {} }Error: "name" not defined in [object Object]
{{customer.name}}{}Error: "name" not defined in undefined
{{customer.name}}{ "customer": {} }, default modeBill to: (silently empty)
{{invoice.purchaseOrder}}value is nullempty, no error
{{invoice.purchaseOrder}}value is ""empty, no error
{{#if notes}}...{{/if}}notes absentblock skipped, no error
{{#if invoice.purchaseOrder}}invoice is {}else block, no error
{{#if invoice.purchaseOrder}}invoice absentError: Cannot read properties of undefined
{{detail}} inside {{#each items}}one item has no detailError: "detail" not defined in [object Object]

So in strict mode, a field is effectively required if the template prints it directly and optional if the template wraps it in {{#if}}. That is the contract you design with:

  • Required fields are printed directly: {{customer.name}}, {{invoice.number}}.
  • Optional fields are wrapped: {{#if detail}}<small>{{detail}}</small>{{/if}}. That one line is why the sample invoice accepts items with and without a detail.
  • Parent objects of optional fields must still be present. Send "invoice": {} rather than leaving invoice out.
  • To mark a value as deliberately empty, send null or "", not nothing.

We applied this to the real sample template, removing one field at a time from the sample data:

Field removedResult
notesRenders; the notes paragraph is omitted
invoice.purchaseOrderRenders; the reference shows a dash
items[0].detailRenders; the first line has no detail text
customer.nameError at line 54: "name" not defined
paymentError at line 89: "instructions" not defined in undefined

The API does not run templates in strict mode. Its engine follows Handlebars' default mode: a missing value prints as an empty string, and a missing parent object does not raise an error. Removing customer.name from the payload therefore produces an invoice with a blank customer, not an error. To get strict-mode safety from the API:

  • For saved templates, set required_fields (dot paths such as customer.name) or a data_schema on the template. POST /templates/{id}/generate then checks the data before rendering and answers 422 validation_error with field set to the path, for example "field": "data.customer.name", without counting a document.
  • For HTML sent with data, nothing is validated on the server. Check the payload against a schema in your code before the call, as shown in the schema section below.

The error handling guide covers the 422 response and why it should not be retried unchanged.

Escaping: double braces, triple braces and untrusted data

{{value}} HTML-escapes the value. Handlebars replaces &, <, >, ", ', ` and = with entities. {{{value}}}, the triple-stash, inserts it raw. We rendered a hostile customer name through both:

{ "name": "<img src=x onerror=\"alert(1)\"> & 'Partners' `=" }
TemplateOutput
<td>{{name}}</td><td>&lt;img src&#x3D;x onerror&#x3D;&quot;alert(1)&quot;&gt; &amp; &#x27;Partners&#x27; &#x60;&#x3D;</td>
<td>{{{name}}}</td><td><img src=x onerror="alert(1)"> & 'Partners' `=</td>

Escaped, the name prints as literal text. Raw, it becomes an image element with an event handler inside the HTML the renderer loads.

Use double braces for everything that comes from customers, users or a model. Agent output is untrusted input: a model can copy text from an email or web page into a field, and that text can contain markup. Raw output also lets data change the layout. An unclosed tag in one field can swallow the rest of the page, and an inserted image or stylesheet can make the renderer fetch outside URLs.

Most requests for triple braces are really requests for line breaks or lists. Model those in the data instead:

  • Multi-line text: send an array of lines and loop over it, as the invoice does for addresses. A string containing <br> prints the tag as text: Line one&lt;br&gt;Line two.
  • Bullet points: send an array and write the <ul> in the template.
  • Emphasis: add a field such as "status": "Unpaid" and let the template style it.

Keep triple braces, if at all, for HTML your own code generated from trusted input and sanitised. The noEscape compile option turns escaping off for a whole template, with the same effect as triple braces everywhere; leave it off.

Format numbers and dates before you send them

A template prints values as JavaScript turns them into strings. These are the actual outputs:

Value sentPrinted as
51605160
0.1 + 0.2 computed in JavaScript0.30000000000000004
1e211e+21
"2026-11-22T00:00:00.000Z"2026-11-22T00:00:00.000Z
falsefalse
["a", "b"]a,b
{ "name": "X" }[object Object]

A formatting helper does not exist unless the template engine registers one: {{formatCurrency total}} failed with "formatCurrency" not defined. Format in the caller. In Node.js, Intl handles currency and locale:

const money = (amount, currency, locale) =>
    new Intl.NumberFormat(locale, { style: "currency", currency }).format(amount);
const day = (iso, locale) =>
    new Intl.DateTimeFormat(locale, { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(new Date(iso));
 
console.log(money(5160, "EUR", "en-GB"));  // "€5,160.00"
console.log(money(5160, "EUR", "de-DE"));  // "5.160,00 €"
console.log(money(98000, "JPY", "ja-JP")); // "¥98,000" (full-width yen sign)
console.log(day("2026-11-22", "en-GB"));   // "22 Nov 2026"
console.log(day("2026-11-22", "en-US"));   // "Nov 22, 2026"

In Python, compute money with Decimal so sums do not drift, then format:

from decimal import Decimal, ROUND_HALF_UP
 
def eur(amount: Decimal) -> str:
    return f"€{amount.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP):,}"
 
lines = [(Decimal("6"), Decimal("120.00")), (Decimal("1"), Decimal("2400.00"))]
print(eur(sum(q * p for q, p in lines)))  # "€3,120.00"
print(eur(Decimal("0.1") + Decimal("0.2")))  # "€0.30"

Check the output fonts if you print non-Latin currency signs: the full-width yen above needs a font that contains it.

Design a data schema an agent can fill

When an AI agent fills a template through a tool such as generate_pdf from the agent quickstart, the data shape is the agent's whole interface to the document. A few choices make it far more reliable:

  • Name fields for what they mean. invoice.dueDate beats d2. The model reads the names.
  • Make display values strings and say how they are formatted in the field description: "already formatted for display, e.g. 22 Nov 2026".
  • Use arrays for anything repeated (line items, address lines, tax rows), each item an object with the same keys.
  • List required fields and match them to what the template prints directly.
  • Reject unknown fields with additionalProperties: false, so a misspelt custmer fails loudly instead of rendering a blank.
  • Bound sizes with maxItems and maxLength so a runaway list does not produce a 300-page PDF.
  • Version it. Put a version in the schema title or ID and change it when the template's fields change.

This is an excerpt of the schema written for the sample invoice. The full schema covers every field the template uses; it is JSON Schema draft-07 so that it runs with the widely installed Ajv 6:

{
  "title": "Invoice template data (v1)",
  "type": "object",
  "required": ["seller", "customer", "invoice", "items", "totals", "payment"],
  "additionalProperties": false,
  "properties": {
    "customer": {
      "type": "object",
      "required": ["name", "address"],
      "additionalProperties": false,
      "properties": {
        "name": { "type": "string", "minLength": 1, "maxLength": 200 },
        "address": { "type": "array", "items": { "type": "string" }, "maxItems": 6 }
      }
    },
    "items": {
      "type": "array",
      "minItems": 1,
      "maxItems": 500,
      "items": {
        "type": "object",
        "required": ["description", "quantity", "unitPrice", "amount"],
        "additionalProperties": false,
        "properties": {
          "description": { "type": "string", "minLength": 1 },
          "detail": { "type": "string" },
          "quantity": { "type": "string" },
          "unitPrice": { "type": "string" },
          "amount": { "type": "string" }
        }
      }
    },
    "notes": { "type": "string" }
  }
}

We validated good and bad payloads against the full schema with Ajv 6.12.6 before rendering anything:

PayloadResult
Sample data.jsonvalid
Sample data-long.json (60 lines, JPY)valid
customer.name removed.customer should have required property 'name'
items sent as a string.items should be array
totals.total sent as the number 5160.totals.total should be string
Empty items plus an unknown discount fieldshould NOT have additional properties (discount) and .items should NOT have fewer than 1 items

The items row matters more than it looks. Without validation, items as a string did not error in Handlebars: {{#each}} treated it as empty and printed "No items". An object in place of the array was looped over by key instead. A schema check turns those silent mistakes into errors with a path.

Run the check in your tool executor before calling the API, and return the errors to the model as a tool result so it can correct the field. A saved template can also carry a data_schema, which the API checks on every generate call. It supports a subset of JSON Schema: type, required, properties, additionalProperties (true or false), items, enum, minLength, maxLength, minimum, maximum, minItems and maxItems, plus annotations such as title and description. Other keywords are rejected when you save the template, so a stored schema never checks less than it appears to. The sample schema uses pattern, which is not in that subset: remove it before storing the schema on a template, and keep the full version in your executor. If an agent only ever fills one template, you can also use the template's schema as the data property of the tool definition, so the model sees the required fields up front.

Test a template locally with the sample files

The invoice template and data are public, so you can reproduce the data binding without an account. Download both files, run npm install handlebars in the same folder, and save this as merge.mjs:

Invoice sample files

Rendered from this template and data with headless Chromium for documentation.

import fs from "node:fs";
import Handlebars from "handlebars";
 
const template = fs.readFileSync("template.html", "utf8");
const data = JSON.parse(fs.readFileSync("data.json", "utf8"));
const html = Handlebars.compile(template, { strict: true })(data);
fs.writeFileSync("invoice.rendered.html", html);

Our run produced 5,667 characters of HTML, identical to the committed invoice.rendered.html that the sample PDF was printed from. Open the merged HTML in a browser to check the data binding, then run render-invoice.mjs from the top of this guide to check the PDF, with the HTML and data or with the data and your saved copy of the template.

Turn the failure cases into tests: one payload per optional field left out, one with every optional field present, one with the longest values you expect, and one invalid payload per required field. Each should either render or fail exactly where you expect.

Checklist

  • Totals, taxes, currency and dates are computed and formatted by the caller.
  • Required fields are printed directly; optional fields are wrapped in {{#if}}, and their parent objects are always sent.
  • Numeric zeros that must print are sent as strings.
  • Untrusted and agent-supplied values use double braces; line breaks and lists are arrays.
  • Each template has a versioned JSON Schema, checked in your executor before every render.
  • Good and bad sample payloads live next to the template and run as tests.

For template design itself, start from the invoice template or report template. For endpoints and options, see the API reference.

Sources

  1. Handlebars: (Pre-)Compilation options (strict, noEscape, assumeObjects) · accessed 23 November 2026
  2. Handlebars: Expressions (HTML escaping and triple-stash) · accessed 23 November 2026
  3. Handlebars: Utility functions (escapeExpression character list) · accessed 23 November 2026
  4. Handlebars: Built-in helpers (if, unless, each, with) · accessed 23 November 2026
  5. Handlebars: Block helpers (chained else blocks) · accessed 23 November 2026
  6. JSON Schema Draft 2020-12 · accessed 23 November 2026

Generate your first PDF with one API call.

Create an account, copy an API key and send HTML, or a template ID with JSON data, from your code or your agent.