Skip to main content

docx_templating/
lib.rs

1//! # docx-templating
2//!
3//! A Rust library for generating Microsoft Word documents (`.docx`) from templates
4//! with variable placeholders, conditional sections, and loops.
5//!
6//! ## Features
7//!
8//! - **Variable replacement**: `{{user.name}}` with nested path support
9//! - **Conditionals**: `{% if condition %} ... {% elif condition %} ... {% else %} ... {% endif %}`
10//! - **Comparisons and boolean logic**: `{% if total > 100 and paid %}`
11//! - **Arithmetic**: `{{price * quantity}}`, `{{subtotal - discount}}`
12//! - **Loops**: `{% for item in items %} ... {% endfor %}`
13//! - **Filters**: `{{name | upper}}`, `{{nickname | default: "friend"}}`,
14//!   `{{total | round: 2}}`, `{{created_at | date: "%Y-%m-%d"}}`, and custom
15//!   filters on [`TemplateOptions`]
16//! - **Headers, footers, footnotes and endnotes**: opt in with
17//!   [`TemplateOptions::headers_and_footers`] and [`TemplateOptions::footnotes`]
18//! - **Safe XML handling**: Automatic escaping, no injection vulnerabilities
19//! - **Typed context**: render accepts JSON or any borrowed `serde::Serialize` value
20//!
21//! ## Architecture
22//!
23//! The crate is a pipeline with typed boundaries:
24//!
25//! 1. **Domain** (`domain`) - the lossless document tree, template binding,
26//!    placement, resolved plan and evaluator. It never touches XML, ZIP or the
27//!    filesystem.
28//! 2. **Adapters** (`adapters`) - parse XML into the document model and write it
29//!    back, and read and write the DOCX package.
30//! 3. **Public API** - `Template`, `Context`, `IntoContext`, `RenderedDocument`,
31//!    options and errors.
32//!
33//! `tests/architecture.rs` enforces the boundary between the domain and the
34//! adapters.
35//!
36//! ## Example
37//!
38//! ```rust,no_run
39//! use docx_templating::Template;
40//! use serde_json::json;
41//!
42//! let data = json!({
43//!     "user": {
44//!         "name": "Ada Lovelace"
45//!     }
46//! });
47//!
48//! let output = Template::from_path("template.docx")?
49//!     .render(data)?;
50//!
51//! output.write_to_file("output.docx")?;
52//! # Ok::<(), docx_templating::Error>(())
53//! ```
54//!
55//! Any borrowed [`serde::Serialize`] value works as the context, so a caller can
56//! pass their own struct instead of building JSON:
57//!
58//! ```rust,no_run
59//! use docx_templating::Template;
60//! use serde::Serialize;
61//!
62//! #[derive(Serialize)]
63//! struct Invoice {
64//!     total: u32,
65//! }
66//!
67//! # fn example() -> docx_templating::Result<()> {
68//! let template = Template::from_path("template.docx")?;
69//! let rendered = template.render(&Invoice { total: 42 })?;
70//! rendered.write_to_file("output.docx")?;
71//! # Ok(())
72//! # }
73//! ```
74//!
75//! For a template that is rendered once, [`render`] loads and renders it in a
76//! single call:
77//!
78//! ```rust,no_run
79//! # fn example() -> docx_templating::Result<()> {
80//! let rendered = docx_templating::render(
81//!     "template.docx",
82//!     serde_json::json!({ "name": "Ada" }),
83//! )?;
84//! rendered.write_to_file("output.docx")?;
85//! # Ok(())
86//! # }
87//! ```
88//!
89//! ## Status
90//!
91//! **Current version: 1.0.0**, with every phase of the roadmap implemented.
92//! Variable replacement, conditionals, paragraph loops, table-row loops,
93//! multi-part rendering and hardening are production-ready.
94//! The public API is frozen for 1.x: new features are additive and breaking
95//! changes wait for 2.0.
96//!
97//! The main document is always rendered. Headers, footers, footnotes and
98//! endnotes are rendered when
99//! [`TemplateOptions::headers_and_footers`] and [`TemplateOptions::footnotes`]
100//! ask for it; otherwise those parts are copied through unchanged.
101//!
102
103#![forbid(unsafe_code)]
104#![deny(
105    missing_docs,
106    missing_debug_implementations,
107    clippy::expect_used,
108    clippy::unwrap_used,
109    clippy::panic,
110    clippy::indexing_slicing
111)]
112
113// Public modules
114pub mod docx;
115pub mod error;
116pub mod package;
117
118// Pipeline layers. The domain is pure; the adapters translate formats.
119mod adapters;
120mod api;
121mod domain;
122mod syntax;
123
124// Public API surface
125mod context;
126mod diagnostic;
127mod filters;
128mod options;
129mod rendered;
130mod template;
131
132// Public re-exports
133pub use context::{Context, ContextError, IntoContext};
134pub use diagnostic::{Diagnostic, diagnose};
135pub use domain::binding::BindingError;
136pub use domain::engine::RenderError;
137pub use domain::plan::PlanError;
138pub use error::{Error, Result, XmlError};
139pub use filters::{FilterError, FilterRegistry};
140pub use options::{LineBreakPolicy, MissingValuePolicy, TemplateOptions};
141pub use rendered::RenderedDocument;
142pub use template::{Template, render};