docx-templating
A Rust library for generating Microsoft Word documents (.docx) from templates with variable placeholders, conditional sections, and loops.
Status: Stable
Current Version: 1.0.0 (all phases complete)
The public API is frozen for 1.x. New features are additive and breaking changes wait for 2.0. The minimum supported Rust version is 1.89.
Implementation Progress
- ✅ Phase 0: Engineering Baseline
- ✅ Phase 1: Package Foundation (ZIP/OPC handling)
- ✅ Phase 2: Text Projection (placeholders split across runs)
- ✅ Phase 3: Template Syntax Parser
- ✅ Phase 4: Context and Data Lookup
- ✅ Phase 5: Inline Variable Replacement
- ✅ Phase 6: Conditionals
- ✅ Phase 7: Paragraph Loops
- ✅ Phase 8: Table Loops and Nested Blocks
- ✅ Phase 9: Headers, Footers, Footnotes and Endnotes
- ✅ Phase 10: Hardening and Performance
- ✅ Pipeline rewrite: lossless document tree, resolved plan tree, pure domain
Every phase of the roadmap is now implemented. The main document is always rendered. Headers, footers, footnotes and endnotes are rendered when TemplateOptions asks for them; otherwise those parts are copied through unchanged.
Features
- Variable substitution:
{{user.name}},{{items.0}},{{item}}and{{.}}(current item in a loop) - Filters:
{{name | upper}},{{nickname | default: "friend"}},{{items | len}},{{total | round: 2}},{{created_at | date: "%Y-%m-%d"}}, chains such as{{name | trim | upper}}, and custom filters onTemplateOptions - Conditionals:
{% if condition %} ... {% elif condition %} ... {% else %} ... {% endif %} - Arithmetic:
{{price * quantity}},{{subtotal - discount}},{{(price + tax) * quantity | fixed: 2}} - Loops:
{% for item in items %} ... {% endfor %}for paragraphs and table rows, with{{@index}},{{@first}}and{{@last}} - Table-row loops: loop markers inside a
<w:tr>duplicate the entire row per element - Multi-paragraph/row blocks: tag lines on their own paragraphs or rows are deleted cleanly with no empty lines or rows left behind
- Conditional rows:
{% if %}aligned with a table row removes the row when false - Nested blocks: conditionals inside loop body cells, loops inside conditionals
- Line break policy: control how
\nin a value is rendered —InsertWordBreak(default, emits<w:br/>) orSplitParagraph(produces separate<w:p>elements inheriting original formatting) - Whitespace preservation:
preserve_whitespaceoption (defaulttrue) controls whetherxml:space="preserve"is added to replacement<w:t>elements with leading/trailing spaces; set tofalseto let Word normalise edge whitespace itself - Safe XML escaping: All user text automatically escaped
- Decompression-bomb protection: ZIP entries with declared uncompressed size > 100 MiB are rejected before decompression begins (
PackageError::EntrySizeExceeded) - Actionable error context:
RenderErrorvariants include the DOCX part name (e.g.word/document.xml) so errors pinpoint exactly where template evaluation failed - Raw-copy passthrough: unchanged ZIP parts are copied verbatim without decompress/recompress when the source exposes its raw archive bytes — transparent to all callers
- Split placeholder handling: Works even when a placeholder spans multiple XML runs
- Flexible context:
renderaccepts aContext, aserde_json::Value, or a borrowedserde::Serializevalue, so a caller can pass their own struct - One shot rendering:
docx_templating::render("template.docx", &data)loads and renders in a single call - Byte in, byte out:
Template::from_bytesaccepts a slice or aVec, andRenderedDocumentimplementsAsRef<[u8]>andInto<Vec<u8>> - Thread safe: a loaded
TemplateisSendandSync, so oneArc<Template>can render on several threads - Streaming output:
Template::render_to_writerwrites the package to anyWrite + Seeksink, andrenderreturns the bytes - Compiler style errors:
diagnoseandTemplate::diagnosticpoint a caret at the paragraph that failed, with a help line - Multi-part templates: placeholders, conditionals and loops work in headers, footers, footnotes and endnotes when the matching option is on
Installation
Usage
use Template;
use json;
let output = from_path?
.render?;
output.write_to_file?;
Variables
Hello {{user.name}}!
Invoice #{{invoice.number}}
First tag: {{tags.0}}
Filters
A filter changes a value before it is inserted. Write it after a pipe, and chain filters left to right. A filter can take one argument after a colon.
{{user.name | upper}}
{{nickname | default: "friend"}}
{{items | len}}
{{tags | join: ", "}}
{{user.name | trim | upper}}
The built in filters are:
| Filter | Effect |
|---|---|
upper |
Upper case a string or scalar |
lower |
Lower case a string or scalar |
trim |
Remove leading and trailing whitespace |
default: "text" |
Replace a missing or null value |
len |
Length of a string, array or object |
join: ", " |
Join an array into text, comma and space by default |
round: 2 |
Round to a number of decimal places, half away from zero |
fixed: 2 |
Format with exactly that many decimal places as text |
thousands |
Group the integer digits in threes, comma by default |
percent: 1 |
Multiply by 100 and append %, with one decimal |
date: "%Y-%m-%d" |
Format a date with a strftime pattern |
timezone: "Europe/Paris" |
Convert an instant to a named time zone |
Numbers
The number filters accept JSON numbers and numeric strings:
{{total | round: 2}} -> 1234.57
{{total | fixed: 2}} -> 1234.57
{{total | thousands}} -> 1,234.57
{{rate | percent: 1}} -> 12.3%
{{total | round: 2 | thousands}} -> 1,234.57
round rounds half away from zero. fixed and percent return text with the
requested number of decimal places. thousands takes an optional separator,
as in {{total | thousands: " "}}. It does not round, so chain round before
thousands when the output should be rounded.
Dates and time zones
The dates feature adds date and timezone. It is on by default.
{{created_at | date: "%Y-%m-%d"}}
{{created_at | date: "%d %B %Y at %H:%M"}}
{{created_at | timezone: "Europe/Paris" | date: "%H:%M"}}
date accepts an ISO 8601 date or date and time, an instant with an offset,
or a number of epoch seconds. It uses strftime patterns such as %Y, %m,
%d, %H, %M, %S, %B and %A. A value without an offset is formatted
as written, a value with an offset is formatted in that offset, and epoch
seconds are read in UTC.
timezone converts an instant to a named IANA zone and returns an ISO 8601
value that date can format. The name may be any IANA zone such as
America/New_York, or local for the system zone. A value with an offset is
converted to the target zone. A value without an offset keeps its clock time
and takes the target zone, so a local appointment reads the same before and
after.
Turn the date filters off to drop the dependency:
= { = "1.0.0", = false }
Filters also work in conditions and loop iterables:
{% if items | len %}We have items.{% endif %}
{% for tag in tags | default: "none" %}{{tag | upper}}{% endfor %}
A missing path becomes null, so default can supply a fallback. Without a
filter, a missing path still follows the missing value policy.
Register or replace a filter on the options. The closure receives the current value and the optional argument:
use ;
use Value;
let options = default.filter;
let output = from_path?
.with_options
.render?;
An unknown filter reports RenderError::UnknownFilter, and a filter that rejects
its value reports RenderError::FilterFailed with the reason. Both name the
filter and the DOCX part.
Conditionals
Block tags are removed from the output; only the chosen branch content remains.
Inline (tag and content in the same paragraph):
{% if user.active %}Welcome back, {{user.name}}!{% endif %}
{% if user.vip %}VIP benefits apply.{% else %}Standard access.{% endif %}
{% if not user.active %}Your account is inactive.{% endif %}
Multi-paragraph (each tag on its own line, as Word naturally produces):
{% if user.active %}
Welcome back, {{user.name}}!
{% endif %}
When the condition is true, the tag paragraphs are removed and the body paragraph is kept with variables substituted. When false, all paragraphs in the block are removed - no empty lines are left behind.
Else if chains
{% elif %} adds more branches, tried in order until one is true. When none
match, the {% else %} branch runs, if there is one:
{% if status == "open" %}Open
{% elif status == "pending" %}Pending
{% elif status == "closed" %}Closed
{% else %}Unknown{% endif %}
{% if total > 100 %}
Large order
{% elif total > 10 %}
Medium order
{% else %}
Small order
{% endif %}
The same rules as if apply: inline chains live in one paragraph, chains that
span paragraphs or table rows remove every unused tag and branch, and every
condition can combine comparisons, boolean logic and arithmetic. Conditions are
evaluated from top to bottom and evaluation stops at the first true one, so a
later branch that would fail on its own never runs. An {% elif %} without an
open if, or an {% elif %} after {% else %}, is rejected when the template
loads.
Comparisons and boolean logic
A condition can compare values and combine the results:
{% if total > 100 %}Approval required.{% endif %}
{% if status == "paid" %}Receipt attached.{% endif %}
{% if status != "cancelled" %}Active order.{% endif %}
{% if quantity <= 0 %}Out of stock.{% endif %}
{% if active and verified %}Account ready.{% endif %}
{% if draft or revised %}Needs review.{% endif %}
{% if not (draft or revised) %}Final.{% endif %}
The operands can be paths, literals, filtered values or parenthesized expressions, so {% if items | len > 0 %} and {% if (total > limit and paid) or approved %} both work. Equality compares any two values and treats 10 and 10.0 as equal. Ordering works for two numbers or two strings; mixing them reports RenderError::InvalidComparison with both types. not binds tighter than and, and and binds tighter than or. and and or short circuit, so the side that cannot change the result is not evaluated.
Comparisons belong in a condition. Using one as text or as a loop iterable reports RenderError::ExpressionNotSupported with a hint.
Arithmetic
Placeholders and conditions can do arithmetic with +, -, *, / and %:
{{price * quantity}}
{{subtotal - discount}}
{{(price + tax) * quantity | fixed: 2}}
{% if price * quantity > 100 %}Approval required.{% endif %}
*, / and % bind tighter than + and -, and parentheses override
either. A leading minus negates a value, as in {{-balance}}. Integer results
stay integers and keep full precision, so {{2 * 3}} writes 6 and
{{10 / 4}} writes 2.5.
Arithmetic works on numbers only. A string, boolean, array, object or missing
value reports RenderError::ArithmeticType, and division or remainder by zero
reports RenderError::DivisionByZero.
A filter after an arithmetic expression applies to the whole result, so
{{price * quantity | fixed: 2}} formats the product. To format one operand,
group it first: {{(price | round: 2) * quantity}}.
Loops
Paragraph loops
Iterate over an array. Tag paragraphs are removed; the body paragraph is duplicated once per element.
Object array:
{% for item in items %}
{{item.name}} — qty {{item.qty}}
{% endfor %}
Primitive array (the loop variable and {{.}} both refer to the element):
{% for tag in tags %}
{{.}}
{% endfor %}
An empty or missing array removes all loop paragraphs without error. A non-array value returns RenderError::ExpectedIterable.
Table-row loops
Place {% for %} and {% endfor %} inside a table to duplicate rows instead of paragraphs.
Multi-row range — each marker in its own row, body rows between them:
| {% for item in items %} | |
| {{item.sku}} | {{item.qty}} |
| {% endfor %} | |
Renders to one data row per element; tag rows are removed.
Same-row — all markers inside a single row:
| {% for item in items %} {{item.sku}} {% endfor %} |
The whole row is cloned once per element; tag text is stripped from each copy.
Conditional rows — {% if %} whose block aligns with a complete row removes or keeps that row:
| {% if item.active %} |
| {{item.name}} |
| {% endif %} |
Loop metadata
Three values describe the current iteration. They work in text, in filters and in conditions.
| Tag | Value |
|---|---|
{{@index}} |
Zero based position of the item |
{{@first}} |
true on the first item |
{{@last}} |
true on the last item |
{% for item in items %}
{{@index + 1}}. {{item.name}}{% if not @last %},{% endif %}
{% endfor %}
Details:
@indexis zero based, so add one for the numbering people expect.- In nested loops
@indexrefers to the innermost loop. The outer index cannot be read. - Outside a loop a metadata tag reports
RenderError::MetaOutsideLoopwith the name. - An unknown name such as
@countreports a render error that names it.
The current item
{{.}} always means the current item, whatever the loop variable is called. The loop variable works too, so with {"tags": ["a", "b"]} both forms render the same text:
{% for tag in tags %}
{{tag}} and {{.}}
{% endfor %}
Use {{.}} for a primitive array, because it survives renaming the loop variable and matches the Mustache and Docxtemplater form. Use the name when the item is an object, since {{item.name}} reaches a field and {{.}} cannot. Rendering an object directly reports RenderError::CannotConvertToText with the value type object.
Missing Value Policy
Control what happens when a variable path is not found in the context:
use ;
let template = from_path?
.with_options;
Line Break Policy
Control how \n (or \r\n) characters in a resolved variable value are rendered. DOCX ignores literal newlines inside <w:t> elements, so the library converts them:
use ;
// InsertWordBreak (default): emits <w:br w:type="textWrapping"/> between segments,
// keeping everything in the same paragraph.
let template = from_path?
.with_options;
// SplitParagraph: splits the containing <w:p> into N separate paragraphs,
// each inheriting the original paragraph and run formatting.
let template = from_path?
.with_options;
Both policies can be combined with MissingValuePolicy:
use ;
let options = default
.missing_value_policy
.line_break_policy;
Whitespace Preservation
By default the library emits xml:space="preserve" on any <w:t> element whose replacement value has leading or trailing spaces, preventing Word from silently stripping them. Set preserve_whitespace(false) to suppress this attribute and let Word apply its own normalisation:
use ;
// Default: preserve edge whitespace in replacement values
let template = from_path?
.with_options; // preserve_whitespace defaults to true
// Opt out: let Word normalise whitespace
let template = from_path?
.with_options;
Headers, Footers and Notes
The main document is always templated. Headers, footers, footnotes and endnotes are copied through unchanged until an option turns them on:
use ;
// Template headers and footers as well as the body
let template = from_path?
.with_options;
// Template footnote and endnote parts
let template = from_path?
.with_options;
Both options can be combined. Every enabled part takes the same syntax as the body, including loops, conditionals and split placeholders:
let template = from_path?
.with_options;
A part that stays disabled is never parsed, so a placeholder looking sequence in it cannot fail the load or the render. An error inside an enabled part names that part, for example word/header1.xml, and Template::diagnostic points at the paragraph in it.
Error Diagnostics
An error can be printed as a compiler style message with a caret under the template text that caused it:
use ;
let bytes = read?;
if let Err = from_bytes
error: unclosed block in word/document.xml at 6..29
--> word/document.xml:2:1
|
2 | {% for item in items %}
| ^^^^^^^^^^^^^^^^^^^^^^^ this block is never closed
|
= help: add the matching closing tag before the enclosing block ends
A template that loaded but failed to render is diagnosed with Template::diagnostic, which adds a help line naming the next step, such as the path that the context is missing.
How It Works
A render runs four steps:
- Load - read the ZIP package, validate the required parts, and read
word/document.xml. - Bind - parse the part into a lossless tree, project runs into logical text, and bind template tags to positions. Unsupported placements fail here with
BindingError. - Evaluate - resolve every tag against the context into a plan. Each loop iteration carries its own nested plan, already evaluated.
- Apply and write - apply the plan to a copy of the tree, serialize the part, and write the package. Every other part is copied verbatim.
Capabilities
- Lossless tree: markup the model does not type passes through byte for byte, so an untouched document round trips exactly.
- Split placeholders:
{{user.andname}}in separate runs are stitched into one logical string. - Block placement: inline ranges, whole paragraphs, and table rows are supported. Anything else fails with a typed error instead of producing broken XML.
- Policies: missing values (
Error,Empty,KeepPlaceholder), line breaks (InsertWordBreak,SplitParagraph), and whitespace preservation. - Safe output: all inserted text is escaped, and ZIP entry names are validated against path traversal.
- Bounded reads: a ZIP entry whose declared uncompressed size exceeds 100 MiB is rejected with
PackageError::EntrySizeExceeded.
Performance
Rendering is linear in the number of tags and blocks. There is no per tag or per iteration scan of the rest of the document, so a document with 10,000 placeholders costs about 10,000 times one tag.
Indicative timings from benches/pipeline.rs. Each row is one cargo bench iteration, and the render rows include writing the output package:
| Workload | Time | Throughput |
|---|---|---|
| Load, 10,000 placeholders | 50 ms | about 200k tags/s |
| Load, 10,000 paragraphs without tags | 32 ms | about 310k blocks/s |
| Render, 10,000 placeholders | 44 ms | about 230k tags/s |
| Render, 10,000 paragraphs without tags | 16 ms | about 625k blocks/s |
| Paragraph loop, 1,000 items | 9 ms | about 110k items/s |
| Table row loop, 1,000 items | 17 ms | about 60k items/s |
A tag costs roughly 4 microseconds end to end, and a table row loop costs about 17 microseconds per row because each row is cloned and stripped of its tags.
These numbers come from an Intel Core i5-10500H running Windows 11 with rustc 1.99.1, best of several runs while an editor and a language server were also running. Measurements on that kind of shared laptop move by tens of percent between runs, so treat the table as an order of magnitude and run the suite on an idle machine for your own baseline:
The suites assert that they rendered the expected number of blocks before they time anything, so a broken fixture fails the run instead of reporting a fast number. tests/stress.rs adds a correctness gate for the same shapes: 5,000 blocks, 50 nested loops, and a byte identical round trip of an untouched document.
Architecture
The crate is one library with a pure core:
- Domain - the lossless document tree, template binding, placement rules, the resolved plan, and the evaluator. It never touches XML, ZIP, or the filesystem.
- Adapters - parse WordprocessingML into the tree and serialize it back, and read and write the DOCX package.
- Public API -
Template,Context,IntoContext,RenderedDocument, options, and errors.
tests/architecture.rs fails the build if the domain reaches for an adapter, quick_xml, zip, the filesystem, or IO.
Module Structure
src/
├── lib.rs # Public re-exports and crate docs
├── error.rs # Error, XmlError
├── options.rs # TemplateOptions, MissingValuePolicy, LineBreakPolicy
├── rendered.rs # RenderedDocument
├── template.rs # Template<S>, constructors, render, free render()
├── context.rs # Context, IntoContext
├── domain/ # Pure model, no IO
│ ├── document/ # Lossless tree, roles, text projection
│ ├── template/ # Template syntax model
│ ├── binding/ # Bind tags to positions, placement errors
│ ├── placement/ # Classify block placement
│ ├── plan/ # Plan, Edit, overlap check, apply
│ └── engine/ # Evaluate a bound template into a plan
├── adapters/ # Format and storage adapters
│ ├── docx/ # Parse and serialize WordprocessingML
│ └── package/ # Package adapter
├── syntax/ # Template syntax parser (crate private)
│ ├── ast.rs
│ ├── span.rs
│ └── parser.rs
├── package/ # ZIP/OPC handling
│ ├── source.rs # PackageSource trait
│ ├── writer.rs # PackageWriter trait
│ ├── zip_source.rs # ZipPackageSource
│ ├── zip_writer.rs # ZipPackageWriter
│ ├── memory_source.rs # InMemoryPackageSource
│ └── validation.rs # Path traversal guards
├── docx/ # Part names and structural validation
│ ├── parts.rs
│ └── validate.rs
└── api/ # Public surface marker
Development
Prerequisites
Rust 1.89 or later. The crate uses the 2024 edition.
Building
Running Tests
Benchmarks
Criterion writes its report to target/criterion. The suite has three groups: load for parsing and binding, render for evaluation plus the package write, and loop for paragraph and table row duplication. The current numbers are in Performance.
Repository Tasks
Two generators write the files that the tests and the examples read. They live in the private xtask package, which is not published, so the crate that reaches crates.io has no binaries:
Both write relative to the working directory, so run them from the repository root. The generated files are committed, so a fresh clone does not need to run either one.
Quality Checks
Documentation
- SPECIFICATION.md — Complete product specification with user stories and business rules
- CHANGELOG.md — Version history
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.