docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Template loading and rendering orchestration.

use crate::Result;
use crate::adapters::docx::{parse_part, serialize};
use crate::context::IntoContext;
use crate::diagnostic::{Diagnostic, View};
use crate::docx::parts::{
    DOCUMENT, is_endnotes, is_footer, is_footnotes, is_header, is_main_document,
};
use crate::domain::binding::{BoundTemplate, bind, text_view};
use crate::domain::document::Document;
use crate::domain::engine::{RenderError, evaluate};
use crate::domain::plan::apply;
use crate::error::Error;
use crate::options::TemplateOptions;
use crate::package::{PackageSource, PackageWriter, ZipPackageSource, ZipPackageWriter};
use crate::rendered::RenderedDocument;
use std::io::Read;
use std::path::Path;

/// A DOCX template ready for rendering.
///
/// The template is loaded once and can be rendered multiple times
/// with different contexts. Parsing and validation happen at load time.
///
/// The type parameter selects the package source and defaults to
/// [`ZipPackageSource`], so `Template` on its own is the file backed template
/// and `Template<InMemoryPackageSource>` is the in memory one.
///
/// # Examples
///
/// ```no_run
/// use docx_templating::Template;
/// use serde_json::json;
///
/// # fn example() -> docx_templating::Result<()> {
/// let template = Template::from_path("template.docx")?;
/// let rendered = template.render(json!({"name": "Ada"}))?;
/// rendered.write_to_file("output.docx")?;
/// # Ok(())
/// # }
/// ```
///
/// # Sharing
///
/// A loaded template is immutable and implements `Send` and `Sync`, so it can
/// be shared across threads:
///
/// ```no_run
/// use docx_templating::Template;
/// use std::sync::Arc;
///
/// # fn example() -> docx_templating::Result<()> {
/// let template = Arc::new(Template::from_path("template.docx")?);
///
/// let handles: Vec<_> = (0..4)
///     .map(|_| {
///         let template = Arc::clone(&template);
///         std::thread::spawn(move || {
///             template.render(serde_json::json!({ "name": "Ada" }))
///         })
///     })
///     .collect();
///
/// for handle in handles {
///     let rendered = handle.join().expect("worker panicked")?;
///     rendered.write_to_file("output.docx")?;
/// }
/// # Ok(())
/// # }
/// ```
pub struct Template<S: PackageSource = ZipPackageSource> {
    source: S,
    options: TemplateOptions,
    document: Document,
    bound: BoundTemplate,
    secondary: Vec<SecondaryPart>,
}

/// A header, footer, footnotes or endnotes part kept as raw bytes.
///
/// These parts are parsed and bound only when
/// [`TemplateOptions::headers_and_footers`] or
/// [`TemplateOptions::footnotes`] turns them on. A template that keeps its
/// placeholders in the body never pays for them, and a placeholder-looking
/// sequence in a disabled part cannot fail the load.
struct SecondaryPart {
    name: String,
    bytes: Vec<u8>,
}

impl SecondaryPart {
    /// Parse and bind the part.
    fn load(&self) -> Result<(Document, BoundTemplate)> {
        let document = parse_part(&self.bytes, &self.name).map_err(crate::error::XmlError::from)?;
        let bound = bind(&document, &self.name)?;
        Ok((document, bound))
    }
}

impl<S: PackageSource + std::fmt::Debug> std::fmt::Debug for Template<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut names: Vec<&str> = vec![DOCUMENT];
        names.extend(self.secondary.iter().map(|part| part.name.as_str()));
        f.debug_struct("Template")
            .field("source", &self.source)
            .field("options", &self.options)
            .field("parts", &names)
            .field("paragraphs", &self.bound.paragraphs().len())
            .field("blocks", &self.bound.blocks().len())
            .finish()
    }
}

impl Template<ZipPackageSource> {
    /// Load a template from a file path.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - File cannot be opened
    /// - ZIP is invalid
    /// - Required DOCX parts are missing
    /// - Template syntax is invalid
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
        let source = ZipPackageSource::from_path(path)?;
        Self::from_source(source)
    }

    /// Load a template from a reader.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Reader cannot be read
    /// - ZIP is invalid
    /// - Required DOCX parts are missing
    /// - Template syntax is invalid
    pub fn from_reader(reader: impl Read) -> Result<Self> {
        let source = ZipPackageSource::from_reader(reader)?;
        Self::from_source(source)
    }

    /// Load a template from raw bytes.
    ///
    /// Accepts anything that converts into a `Vec<u8>`, so `Vec<u8>`, a byte
    /// slice and a byte array all work.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Bytes are not a valid ZIP
    /// - Required DOCX parts are missing
    /// - Template syntax is invalid
    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Result<Self> {
        let source = ZipPackageSource::from_bytes(bytes.into())?;
        Self::from_source(source)
    }
}

impl<S: PackageSource> Template<S> {
    /// Create a template from any package source.
    ///
    /// This is the main initialization path. It:
    /// 1. Validates the package structure
    /// 2. Reads word/document.xml
    /// 3. Parses the part into the document tree
    /// 4. Binds the template syntax to the tree
    pub fn from_source(source: S) -> Result<Self> {
        // Validate package structure
        let part_names = source.part_names()?;
        crate::docx::validate_package(&part_names)?;

        // The main document is parsed and bound at load time. Headers,
        // footers, footnotes and endnotes stay as bytes until an option asks
        // for them.
        let doc_xml = source.read_part(DOCUMENT)?.ok_or_else(|| {
            crate::package::PackageError::MissingRequiredPart(DOCUMENT.to_owned())
        })?;
        let document = parse_part(&doc_xml, DOCUMENT).map_err(crate::error::XmlError::from)?;
        let bound = bind(&document, DOCUMENT)?;

        let mut secondary = Vec::new();
        for name in part_names.iter().filter(|name| is_secondary_part(name)) {
            let bytes = source
                .read_part(name)?
                .ok_or_else(|| crate::package::PackageError::MissingRequiredPart(name.clone()))?;
            secondary.push(SecondaryPart {
                name: name.clone(),
                bytes,
            });
        }

        Ok(Self {
            source,
            options: TemplateOptions::default(),
            document,
            bound,
            secondary,
        })
    }

    /// Set rendering options.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use docx_templating::{Template, TemplateOptions, MissingValuePolicy};
    /// # fn example() -> docx_templating::Result<()> {
    /// let template = Template::from_path("template.docx")?
    ///     .with_options(TemplateOptions::default()
    ///         .missing_value_policy(MissingValuePolicy::Empty));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn with_options(mut self, options: TemplateOptions) -> Self {
        self.options = options;
        self
    }

    /// Build a compiler style diagnostic for an error from this template.
    ///
    /// Use it for the errors [`Template::render`] returns. The diagnostic
    /// shows the message, the part, and a help line naming the next step.
    ///
    /// Errors raised while loading have no template to point at, because
    /// loading stopped. Use [`diagnose`](crate::diagnose) with the original
    /// package bytes for those.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use docx_templating::Template;
    /// # fn example() -> docx_templating::Result<()> {
    /// let template = Template::from_path("template.docx")?;
    ///
    /// if let Err(error) = template.render(serde_json::json!({})) {
    ///     eprintln!("{}", template.diagnostic(&error));
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn diagnostic(&self, error: &Error) -> Diagnostic {
        let primary = Diagnostic::with_view(error, &self.primary_view());
        if primary.line().is_some() {
            return primary;
        }

        for part in &self.secondary {
            let Ok(document) = parse_part(&part.bytes, &part.name) else {
                continue;
            };
            let (text, paragraphs) = text_view(&document, &part.name);
            let view = View::new(&part.name, &text, &paragraphs);
            let diagnostic = Diagnostic::with_view(error, &view);
            if diagnostic.line().is_some() {
                return diagnostic;
            }
        }

        primary
    }

    /// A diagnostic view of the main document part.
    fn primary_view(&self) -> View {
        let paragraphs: Vec<_> = self
            .bound
            .paragraphs()
            .iter()
            .map(|paragraph| paragraph.text_start..paragraph.text_end)
            .collect();
        View::new(self.bound.part(), self.bound.text(), &paragraphs)
    }

    /// Render the template with the given context.
    ///
    /// Accepts a [`crate::Context`], a [`serde_json::Value`] such as the result of
    /// [`serde_json::json!`], or a reference to any [`serde::Serialize`] value.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - The context cannot be serialized to JSON
    /// - Context resolution fails
    /// - Missing variables (with `MissingValuePolicy::Error`)
    /// - Applying the render plan fails
    /// - ZIP writing fails
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use docx_templating::Template;
    /// # use serde::Serialize;
    /// # fn example() -> docx_templating::Result<()> {
    /// #[derive(Serialize)]
    /// struct Invoice {
    ///     total: u32,
    /// }
    ///
    /// let template = Template::from_path("template.docx")?;
    /// let invoice = Invoice { total: 42 };
    /// let rendered = template.render(&invoice)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn render(&self, context: impl IntoContext) -> Result<RenderedDocument> {
        let mut output = Vec::new();
        self.render_to_writer(context, std::io::Cursor::new(&mut output))?;
        Ok(RenderedDocument::new(output))
    }

    /// Render the template into an existing writer.
    ///
    /// This is [`Template::render`] without the intermediate `Vec<u8>`: the
    /// package is written straight to `writer`. Use it for a file, a socket, or
    /// any other `Write + Seek` destination.
    ///
    /// The rendered XML is still built in memory, because the plan is applied
    /// to a copy of the parsed tree. What this method avoids is holding the
    /// finished ZIP in memory as well.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`Template::render`], plus any error the
    /// writer raises.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use docx_templating::Template;
    /// # fn example() -> docx_templating::Result<()> {
    /// let template = Template::from_path("template.docx")?;
    /// let file = std::fs::File::create("output.docx")?;
    /// template.render_to_writer(serde_json::json!({ "name": "Ada" }), file)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn render_to_writer(
        &self,
        context: impl IntoContext,
        writer: impl std::io::Write + std::io::Seek,
    ) -> Result<()> {
        let context = context.into_context()?;
        let mut package = ZipPackageWriter::new(writer);
        let mut written: Vec<&str> = Vec::with_capacity(1 + self.secondary.len());

        // The main document is always rendered.
        let plan = evaluate(&self.document, &self.bound, &context, &self.options)?;
        let root = apply(self.document.root(), &plan, self.document.word_prefix())
            .map_err(RenderError::from)?;
        let rendered_document = Document::new(
            self.document.prolog().to_vec(),
            root,
            self.document.epilogue().to_vec(),
            self.document.word_prefix().to_owned(),
        );
        package.write_part(DOCUMENT, &serialize(&rendered_document))?;
        written.push(DOCUMENT);

        // Render the secondary parts the options ask for.
        for part in &self.secondary {
            if !self.renders(&part.name) {
                continue;
            }
            let (document, bound) = part.load()?;
            let plan = evaluate(&document, &bound, &context, &self.options)?;
            let root =
                apply(document.root(), &plan, document.word_prefix()).map_err(RenderError::from)?;
            let rendered_document = Document::new(
                document.prolog().to_vec(),
                root,
                document.epilogue().to_vec(),
                document.word_prefix().to_owned(),
            );
            package.write_part(&part.name, &serialize(&rendered_document))?;
            written.push(&part.name);
        }

        // Copy every part that was not rendered, including the parts whose
        // processing is switched off.
        for name in self.source.part_names()? {
            if !written.contains(&name.as_str()) {
                package.copy_part(&self.source, &name)?;
            }
        }

        package.finish()?;
        Ok(())
    }

    /// Whether a part is rendered with the current options.
    ///
    /// The main document is always rendered. Headers and footers follow
    /// [`TemplateOptions::headers_and_footers`], and footnotes and endnotes
    /// follow [`TemplateOptions::footnotes`].
    fn renders(&self, name: &str) -> bool {
        if is_main_document(name) {
            return true;
        }
        if is_header(name) || is_footer(name) {
            return self.options.headers_and_footers;
        }
        if is_footnotes(name) || is_endnotes(name) {
            return self.options.footnotes;
        }
        false
    }
}

/// Whether a part other than the main document can hold template syntax.
fn is_secondary_part(name: &str) -> bool {
    is_header(name) || is_footer(name) || is_footnotes(name) || is_endnotes(name)
}

/// Load a template from a file and render it in one call.
///
/// This wraps [`Template::from_path`] and [`Template::render`] for the common
/// case of a template that is rendered once. When the same template is rendered
/// several times, load it with [`Template::from_path`] and call
/// [`Template::render`] on it, because loading is the expensive step.
///
/// The context accepts the same values as [`Template::render`]: a
/// [`crate::Context`], a [`serde_json::Value`], or a reference to any
/// [`serde::Serialize`] value.
///
/// # Errors
///
/// Returns the same errors as [`Template::from_path`] and [`Template::render`].
///
/// # Examples
///
/// ```no_run
/// # fn example() -> docx_templating::Result<()> {
/// let rendered = docx_templating::render(
///     "template.docx",
///     serde_json::json!({ "name": "Ada" }),
/// )?;
/// rendered.write_to_file("output.docx")?;
/// # Ok(())
/// # }
/// ```
pub fn render(path: impl AsRef<Path>, context: impl IntoContext) -> Result<RenderedDocument> {
    Template::from_path(path)?.render(context)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

    use super::*;
    use crate::package::InMemoryPackageSource;
    use serde_json::json;

    fn make_test_template(logical_text: &str) -> Template<InMemoryPackageSource> {
        let mut source = InMemoryPackageSource::new();

        // Add required DOCX parts
        source.add_part(
            "[Content_Types].xml",
            br#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"></Types>"#.to_vec(),
        );
        source.add_part(
            "_rels/.rels",
            br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>"#.to_vec(),
        );

        // Add document.xml with the template text
        let doc_xml = format!(
            r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>{}</w:t></w:r></w:p></w:body></w:document>"#,
            logical_text
        );
        source.add_part("word/document.xml", doc_xml.into_bytes());

        Template::from_source(source).unwrap()
    }

    /// Read `word/document.xml` back out of a rendered package.
    fn document_xml(rendered: &RenderedDocument) -> String {
        use std::io::Cursor;
        use zip::ZipArchive;

        let cursor = Cursor::new(rendered.as_bytes());
        let mut archive = ZipArchive::new(cursor).unwrap();
        let mut doc_file = archive.by_name("word/document.xml").unwrap();

        let mut doc_xml = String::new();
        std::io::Read::read_to_string(&mut doc_file, &mut doc_xml).unwrap();
        doc_xml
    }

    #[test]
    fn from_source_validates_package() {
        let source = InMemoryPackageSource::new();
        let result = Template::from_source(source);
        assert!(result.is_err());
    }

    #[test]
    fn from_source_parses_ast() {
        let template = make_test_template("Hello {{name}}!");
        let inline = template.bound.inline();
        assert_eq!(inline.len(), 1);
        assert_eq!(inline[0].nodes.len(), 3); // Text, Variable, Text
    }

    #[test]
    fn with_options_sets_config() {
        let template = make_test_template("{{name}}").with_options(
            TemplateOptions::default()
                .missing_value_policy(crate::options::MissingValuePolicy::Empty),
        );

        assert_eq!(
            template.options.missing_value_policy,
            crate::options::MissingValuePolicy::Empty
        );
    }

    #[test]
    fn render_replaces_variable() {
        let template = make_test_template("Hello {{name}}!");
        let rendered = template.render(json!({"name": "Ada"})).unwrap();

        assert!(document_xml(&rendered).contains("Hello Ada!"));
    }

    #[test]
    fn render_accepts_a_borrowed_struct() {
        #[derive(serde::Serialize)]
        struct Data {
            name: &'static str,
        }

        let template = make_test_template("Hello {{name}}!");
        let rendered = template.render(&Data { name: "Ada" }).unwrap();

        assert!(document_xml(&rendered).contains("Hello Ada!"));
    }

    #[test]
    fn render_handles_missing_with_error_policy() {
        let template = make_test_template("Hello {{missing}}!");
        let result = template.render(json!({}));
        assert!(result.is_err());
    }

    #[test]
    fn render_handles_missing_with_empty_policy() {
        let template = make_test_template("Hello {{missing}}!").with_options(
            TemplateOptions::default()
                .missing_value_policy(crate::options::MissingValuePolicy::Empty),
        );

        let rendered = template.render(json!({})).unwrap();

        assert!(document_xml(&rendered).contains("Hello !"));
    }
}