Templates
docxio can load existing .docx files as templates and replace {{placeholder}} tokens with dynamic values.
Loading a template​
import { loadTemplate } from "docxio";
const templateBytes = await Bun.file("template.docx").bytes();
const tpl = await loadTemplate(templateBytes);
// Inspect available placeholder slots
console.log("Slots:", tpl.slots); // ["title", "author", "date", ...]
The loadTemplate function parses the .docx archive and scans for {{placeholder}} tokens in the document body. It returns a template object with a slots array listing all discovered placeholders.
Simple text replacement​
import { loadTemplate, fillTemplate } from "docxio";
const tpl = await loadTemplate(templateBytes);
const patchedBytes = await fillTemplate(tpl, {
title: "Q4 Financial Report",
author: "Jane Doe",
date: "2025-12-31",
});
await Bun.write("filled.docx", patchedBytes);
String values replace the {{placeholder}} text inline, preserving the surrounding paragraph formatting.
Structured slot filling​
For rich content (tables, styled paragraphs, images), use the <Template> and <Slot> JSX components:
import { loadTemplate, render, Template, Slot } from "docxio";
const tpl = await loadTemplate(templateBytes);
const doc = (
<Template src={tpl} values={{ title: "Q4 Report", author: "Jane Doe" }}>
<Slot name="content">
<paragraph alignment="center">
<run bold fontSize={28}>Revenue Summary</run>
</paragraph>
<table borders="single" width={7500}>
<row>
<cell><paragraph><run bold>Metric</run></paragraph></cell>
<cell><paragraph><run bold>Value</run></paragraph></cell>
</row>
<row>
<cell><paragraph><run>Revenue</run></paragraph></cell>
<cell><paragraph><run>$1.2M</run></paragraph></cell>
</row>
</table>
</Slot>
</Template>
);
const bytes = await render(doc);
When a <Slot> is used, the entire paragraph containing {{content}} is replaced with the rendered OOXML from the slot's children.
Mixing text and slot values​
You can combine simple string replacements (values prop) with structured <Slot> children:
<Template src={tpl} values={{ title: "Report", date: "2025-01-01" }}>
<Slot name="summary">
<paragraph><run bold>Executive Summary</run></paragraph>
<paragraph><run>This quarter showed strong growth...</run></paragraph>
</Slot>
</Template>
Template API reference​
| Export | Description |
|---|---|
loadTemplate(bytes) | Parse .docx bytes, detect {{slots}}, return template object |
fillTemplate(tpl, values) | Replace slots with string values, return patched .docx bytes |
Template | JSX component for template-based rendering with <Slot> support |
Slot | JSX component for injecting structured content into a named slot |
SlotValue type​
Slot values can be either strings (for simple text replacement) or DocumentNode trees (for structured content):
type SlotValue = string | DocumentNode;