Skip to main content

Crate docx_templating

Crate docx_templating 

Source
Expand description

§docx-templating

A Rust library for generating Microsoft Word documents (.docx) from templates with variable placeholders, conditional sections, and loops.

§Features

  • Variable replacement: {{user.name}} with nested path support
  • Conditionals: {% if condition %} ... {% elif condition %} ... {% else %} ... {% endif %}
  • Comparisons and boolean logic: {% if total > 100 and paid %}
  • Arithmetic: {{price * quantity}}, {{subtotal - discount}}
  • Loops: {% for item in items %} ... {% endfor %}
  • Filters: {{name | upper}}, {{nickname | default: "friend"}}, {{total | round: 2}}, {{created_at | date: "%Y-%m-%d"}}, and custom filters on TemplateOptions
  • Headers, footers, footnotes and endnotes: opt in with TemplateOptions::headers_and_footers and TemplateOptions::footnotes
  • Safe XML handling: Automatic escaping, no injection vulnerabilities
  • Typed context: render accepts JSON or any borrowed serde::Serialize value

§Architecture

The crate is a pipeline with typed boundaries:

  1. Domain (domain) - the lossless document tree, template binding, placement, resolved plan and evaluator. It never touches XML, ZIP or the filesystem.
  2. Adapters (adapters) - parse XML into the document model and write it back, and read and write the DOCX package.
  3. Public API - Template, Context, IntoContext, RenderedDocument, options and errors.

tests/architecture.rs enforces the boundary between the domain and the adapters.

§Example

use docx_templating::Template;
use serde_json::json;

let data = json!({
    "user": {
        "name": "Ada Lovelace"
    }
});

let output = Template::from_path("template.docx")?
    .render(data)?;

output.write_to_file("output.docx")?;

Any borrowed serde::Serialize value works as the context, so a caller can pass their own struct instead of building JSON:

use docx_templating::Template;
use serde::Serialize;

#[derive(Serialize)]
struct Invoice {
    total: u32,
}

let template = Template::from_path("template.docx")?;
let rendered = template.render(&Invoice { total: 42 })?;
rendered.write_to_file("output.docx")?;

For a template that is rendered once, render loads and renders it in a single call:

let rendered = docx_templating::render(
    "template.docx",
    serde_json::json!({ "name": "Ada" }),
)?;
rendered.write_to_file("output.docx")?;

§Status

Current version: 1.0.0, with every phase of the roadmap implemented. Variable replacement, conditionals, paragraph loops, table-row loops, multi-part rendering and hardening are production-ready. The public API is frozen for 1.x: new features are additive and breaking changes wait for 2.0.

The main document is always rendered. Headers, footers, footnotes and endnotes are rendered when TemplateOptions::headers_and_footers and TemplateOptions::footnotes ask for it; otherwise those parts are copied through unchanged.

Re-exports§

pub use error::Error;
pub use error::Result;
pub use error::XmlError;

Modules§

docx
DOCX-specific knowledge and conventions.
error
Error types for the docx-templating library.
package
DOCX package (ZIP/OPC) handling.

Structs§

Context
Template data context wrapping JSON values.
Diagnostic
A multi line, compiler style rendering of an error.
FilterError
An error raised by a filter.
FilterRegistry
A named set of filters.
RenderedDocument
A rendered DOCX document.
Template
A DOCX template ready for rendering.
TemplateOptions
Configuration options for template rendering.

Enums§

BindingError
An error raised while binding.
ContextError
Context error type.
LineBreakPolicy
Policy for handling newline characters (\n, \r\n) in resolved variable values.
MissingValuePolicy
Policy for handling missing values during rendering.
PlanError
An error raised while building a plan.
RenderError
Render error type.

Traits§

IntoContext
Anything that can be turned into a Context.

Functions§

diagnose
Render an error against the DOCX package it came from.
render
Load a template from a file and render it in one call.