Skip to main content

docx_templating/
template.rs

1//! Template loading and rendering orchestration.
2
3use crate::Result;
4use crate::adapters::docx::{parse_part, serialize};
5use crate::context::IntoContext;
6use crate::diagnostic::{Diagnostic, View};
7use crate::docx::parts::{
8    DOCUMENT, is_endnotes, is_footer, is_footnotes, is_header, is_main_document,
9};
10use crate::domain::binding::{BoundTemplate, bind, text_view};
11use crate::domain::document::Document;
12use crate::domain::engine::{RenderError, evaluate};
13use crate::domain::plan::apply;
14use crate::error::Error;
15use crate::options::TemplateOptions;
16use crate::package::{PackageSource, PackageWriter, ZipPackageSource, ZipPackageWriter};
17use crate::rendered::RenderedDocument;
18use std::io::Read;
19use std::path::Path;
20
21/// A DOCX template ready for rendering.
22///
23/// The template is loaded once and can be rendered multiple times
24/// with different contexts. Parsing and validation happen at load time.
25///
26/// The type parameter selects the package source and defaults to
27/// [`ZipPackageSource`], so `Template` on its own is the file backed template
28/// and `Template<InMemoryPackageSource>` is the in memory one.
29///
30/// # Examples
31///
32/// ```no_run
33/// use docx_templating::Template;
34/// use serde_json::json;
35///
36/// # fn example() -> docx_templating::Result<()> {
37/// let template = Template::from_path("template.docx")?;
38/// let rendered = template.render(json!({"name": "Ada"}))?;
39/// rendered.write_to_file("output.docx")?;
40/// # Ok(())
41/// # }
42/// ```
43///
44/// # Sharing
45///
46/// A loaded template is immutable and implements `Send` and `Sync`, so it can
47/// be shared across threads:
48///
49/// ```no_run
50/// use docx_templating::Template;
51/// use std::sync::Arc;
52///
53/// # fn example() -> docx_templating::Result<()> {
54/// let template = Arc::new(Template::from_path("template.docx")?);
55///
56/// let handles: Vec<_> = (0..4)
57///     .map(|_| {
58///         let template = Arc::clone(&template);
59///         std::thread::spawn(move || {
60///             template.render(serde_json::json!({ "name": "Ada" }))
61///         })
62///     })
63///     .collect();
64///
65/// for handle in handles {
66///     let rendered = handle.join().expect("worker panicked")?;
67///     rendered.write_to_file("output.docx")?;
68/// }
69/// # Ok(())
70/// # }
71/// ```
72pub struct Template<S: PackageSource = ZipPackageSource> {
73    source: S,
74    options: TemplateOptions,
75    document: Document,
76    bound: BoundTemplate,
77    secondary: Vec<SecondaryPart>,
78}
79
80/// A header, footer, footnotes or endnotes part kept as raw bytes.
81///
82/// These parts are parsed and bound only when
83/// [`TemplateOptions::headers_and_footers`] or
84/// [`TemplateOptions::footnotes`] turns them on. A template that keeps its
85/// placeholders in the body never pays for them, and a placeholder-looking
86/// sequence in a disabled part cannot fail the load.
87struct SecondaryPart {
88    name: String,
89    bytes: Vec<u8>,
90}
91
92impl SecondaryPart {
93    /// Parse and bind the part.
94    fn load(&self) -> Result<(Document, BoundTemplate)> {
95        let document = parse_part(&self.bytes, &self.name).map_err(crate::error::XmlError::from)?;
96        let bound = bind(&document, &self.name)?;
97        Ok((document, bound))
98    }
99}
100
101impl<S: PackageSource + std::fmt::Debug> std::fmt::Debug for Template<S> {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        let mut names: Vec<&str> = vec![DOCUMENT];
104        names.extend(self.secondary.iter().map(|part| part.name.as_str()));
105        f.debug_struct("Template")
106            .field("source", &self.source)
107            .field("options", &self.options)
108            .field("parts", &names)
109            .field("paragraphs", &self.bound.paragraphs().len())
110            .field("blocks", &self.bound.blocks().len())
111            .finish()
112    }
113}
114
115impl Template<ZipPackageSource> {
116    /// Load a template from a file path.
117    ///
118    /// # Errors
119    ///
120    /// Returns error if:
121    /// - File cannot be opened
122    /// - ZIP is invalid
123    /// - Required DOCX parts are missing
124    /// - Template syntax is invalid
125    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
126        let source = ZipPackageSource::from_path(path)?;
127        Self::from_source(source)
128    }
129
130    /// Load a template from a reader.
131    ///
132    /// # Errors
133    ///
134    /// Returns error if:
135    /// - Reader cannot be read
136    /// - ZIP is invalid
137    /// - Required DOCX parts are missing
138    /// - Template syntax is invalid
139    pub fn from_reader(reader: impl Read) -> Result<Self> {
140        let source = ZipPackageSource::from_reader(reader)?;
141        Self::from_source(source)
142    }
143
144    /// Load a template from raw bytes.
145    ///
146    /// Accepts anything that converts into a `Vec<u8>`, so `Vec<u8>`, a byte
147    /// slice and a byte array all work.
148    ///
149    /// # Errors
150    ///
151    /// Returns error if:
152    /// - Bytes are not a valid ZIP
153    /// - Required DOCX parts are missing
154    /// - Template syntax is invalid
155    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Result<Self> {
156        let source = ZipPackageSource::from_bytes(bytes.into())?;
157        Self::from_source(source)
158    }
159}
160
161impl<S: PackageSource> Template<S> {
162    /// Create a template from any package source.
163    ///
164    /// This is the main initialization path. It:
165    /// 1. Validates the package structure
166    /// 2. Reads word/document.xml
167    /// 3. Parses the part into the document tree
168    /// 4. Binds the template syntax to the tree
169    pub fn from_source(source: S) -> Result<Self> {
170        // Validate package structure
171        let part_names = source.part_names()?;
172        crate::docx::validate_package(&part_names)?;
173
174        // The main document is parsed and bound at load time. Headers,
175        // footers, footnotes and endnotes stay as bytes until an option asks
176        // for them.
177        let doc_xml = source.read_part(DOCUMENT)?.ok_or_else(|| {
178            crate::package::PackageError::MissingRequiredPart(DOCUMENT.to_owned())
179        })?;
180        let document = parse_part(&doc_xml, DOCUMENT).map_err(crate::error::XmlError::from)?;
181        let bound = bind(&document, DOCUMENT)?;
182
183        let mut secondary = Vec::new();
184        for name in part_names.iter().filter(|name| is_secondary_part(name)) {
185            let bytes = source
186                .read_part(name)?
187                .ok_or_else(|| crate::package::PackageError::MissingRequiredPart(name.clone()))?;
188            secondary.push(SecondaryPart {
189                name: name.clone(),
190                bytes,
191            });
192        }
193
194        Ok(Self {
195            source,
196            options: TemplateOptions::default(),
197            document,
198            bound,
199            secondary,
200        })
201    }
202
203    /// Set rendering options.
204    ///
205    /// # Examples
206    ///
207    /// ```no_run
208    /// # use docx_templating::{Template, TemplateOptions, MissingValuePolicy};
209    /// # fn example() -> docx_templating::Result<()> {
210    /// let template = Template::from_path("template.docx")?
211    ///     .with_options(TemplateOptions::default()
212    ///         .missing_value_policy(MissingValuePolicy::Empty));
213    /// # Ok(())
214    /// # }
215    /// ```
216    #[must_use]
217    pub fn with_options(mut self, options: TemplateOptions) -> Self {
218        self.options = options;
219        self
220    }
221
222    /// Build a compiler style diagnostic for an error from this template.
223    ///
224    /// Use it for the errors [`Template::render`] returns. The diagnostic
225    /// shows the message, the part, and a help line naming the next step.
226    ///
227    /// Errors raised while loading have no template to point at, because
228    /// loading stopped. Use [`diagnose`](crate::diagnose) with the original
229    /// package bytes for those.
230    ///
231    /// # Examples
232    ///
233    /// ```no_run
234    /// # use docx_templating::Template;
235    /// # fn example() -> docx_templating::Result<()> {
236    /// let template = Template::from_path("template.docx")?;
237    ///
238    /// if let Err(error) = template.render(serde_json::json!({})) {
239    ///     eprintln!("{}", template.diagnostic(&error));
240    /// }
241    /// # Ok(())
242    /// # }
243    /// ```
244    #[must_use]
245    pub fn diagnostic(&self, error: &Error) -> Diagnostic {
246        let primary = Diagnostic::with_view(error, &self.primary_view());
247        if primary.line().is_some() {
248            return primary;
249        }
250
251        for part in &self.secondary {
252            let Ok(document) = parse_part(&part.bytes, &part.name) else {
253                continue;
254            };
255            let (text, paragraphs) = text_view(&document, &part.name);
256            let view = View::new(&part.name, &text, &paragraphs);
257            let diagnostic = Diagnostic::with_view(error, &view);
258            if diagnostic.line().is_some() {
259                return diagnostic;
260            }
261        }
262
263        primary
264    }
265
266    /// A diagnostic view of the main document part.
267    fn primary_view(&self) -> View {
268        let paragraphs: Vec<_> = self
269            .bound
270            .paragraphs()
271            .iter()
272            .map(|paragraph| paragraph.text_start..paragraph.text_end)
273            .collect();
274        View::new(self.bound.part(), self.bound.text(), &paragraphs)
275    }
276
277    /// Render the template with the given context.
278    ///
279    /// Accepts a [`crate::Context`], a [`serde_json::Value`] such as the result of
280    /// [`serde_json::json!`], or a reference to any [`serde::Serialize`] value.
281    ///
282    /// # Errors
283    ///
284    /// Returns error if:
285    /// - The context cannot be serialized to JSON
286    /// - Context resolution fails
287    /// - Missing variables (with `MissingValuePolicy::Error`)
288    /// - Applying the render plan fails
289    /// - ZIP writing fails
290    ///
291    /// # Examples
292    ///
293    /// ```no_run
294    /// # use docx_templating::Template;
295    /// # use serde::Serialize;
296    /// # fn example() -> docx_templating::Result<()> {
297    /// #[derive(Serialize)]
298    /// struct Invoice {
299    ///     total: u32,
300    /// }
301    ///
302    /// let template = Template::from_path("template.docx")?;
303    /// let invoice = Invoice { total: 42 };
304    /// let rendered = template.render(&invoice)?;
305    /// # Ok(())
306    /// # }
307    /// ```
308    pub fn render(&self, context: impl IntoContext) -> Result<RenderedDocument> {
309        let mut output = Vec::new();
310        self.render_to_writer(context, std::io::Cursor::new(&mut output))?;
311        Ok(RenderedDocument::new(output))
312    }
313
314    /// Render the template into an existing writer.
315    ///
316    /// This is [`Template::render`] without the intermediate `Vec<u8>`: the
317    /// package is written straight to `writer`. Use it for a file, a socket, or
318    /// any other `Write + Seek` destination.
319    ///
320    /// The rendered XML is still built in memory, because the plan is applied
321    /// to a copy of the parsed tree. What this method avoids is holding the
322    /// finished ZIP in memory as well.
323    ///
324    /// # Errors
325    ///
326    /// Returns the same errors as [`Template::render`], plus any error the
327    /// writer raises.
328    ///
329    /// # Examples
330    ///
331    /// ```no_run
332    /// # use docx_templating::Template;
333    /// # fn example() -> docx_templating::Result<()> {
334    /// let template = Template::from_path("template.docx")?;
335    /// let file = std::fs::File::create("output.docx")?;
336    /// template.render_to_writer(serde_json::json!({ "name": "Ada" }), file)?;
337    /// # Ok(())
338    /// # }
339    /// ```
340    pub fn render_to_writer(
341        &self,
342        context: impl IntoContext,
343        writer: impl std::io::Write + std::io::Seek,
344    ) -> Result<()> {
345        let context = context.into_context()?;
346        let mut package = ZipPackageWriter::new(writer);
347        let mut written: Vec<&str> = Vec::with_capacity(1 + self.secondary.len());
348
349        // The main document is always rendered.
350        let plan = evaluate(&self.document, &self.bound, &context, &self.options)?;
351        let root = apply(self.document.root(), &plan, self.document.word_prefix())
352            .map_err(RenderError::from)?;
353        let rendered_document = Document::new(
354            self.document.prolog().to_vec(),
355            root,
356            self.document.epilogue().to_vec(),
357            self.document.word_prefix().to_owned(),
358        );
359        package.write_part(DOCUMENT, &serialize(&rendered_document))?;
360        written.push(DOCUMENT);
361
362        // Render the secondary parts the options ask for.
363        for part in &self.secondary {
364            if !self.renders(&part.name) {
365                continue;
366            }
367            let (document, bound) = part.load()?;
368            let plan = evaluate(&document, &bound, &context, &self.options)?;
369            let root =
370                apply(document.root(), &plan, document.word_prefix()).map_err(RenderError::from)?;
371            let rendered_document = Document::new(
372                document.prolog().to_vec(),
373                root,
374                document.epilogue().to_vec(),
375                document.word_prefix().to_owned(),
376            );
377            package.write_part(&part.name, &serialize(&rendered_document))?;
378            written.push(&part.name);
379        }
380
381        // Copy every part that was not rendered, including the parts whose
382        // processing is switched off.
383        for name in self.source.part_names()? {
384            if !written.contains(&name.as_str()) {
385                package.copy_part(&self.source, &name)?;
386            }
387        }
388
389        package.finish()?;
390        Ok(())
391    }
392
393    /// Whether a part is rendered with the current options.
394    ///
395    /// The main document is always rendered. Headers and footers follow
396    /// [`TemplateOptions::headers_and_footers`], and footnotes and endnotes
397    /// follow [`TemplateOptions::footnotes`].
398    fn renders(&self, name: &str) -> bool {
399        if is_main_document(name) {
400            return true;
401        }
402        if is_header(name) || is_footer(name) {
403            return self.options.headers_and_footers;
404        }
405        if is_footnotes(name) || is_endnotes(name) {
406            return self.options.footnotes;
407        }
408        false
409    }
410}
411
412/// Whether a part other than the main document can hold template syntax.
413fn is_secondary_part(name: &str) -> bool {
414    is_header(name) || is_footer(name) || is_footnotes(name) || is_endnotes(name)
415}
416
417/// Load a template from a file and render it in one call.
418///
419/// This wraps [`Template::from_path`] and [`Template::render`] for the common
420/// case of a template that is rendered once. When the same template is rendered
421/// several times, load it with [`Template::from_path`] and call
422/// [`Template::render`] on it, because loading is the expensive step.
423///
424/// The context accepts the same values as [`Template::render`]: a
425/// [`crate::Context`], a [`serde_json::Value`], or a reference to any
426/// [`serde::Serialize`] value.
427///
428/// # Errors
429///
430/// Returns the same errors as [`Template::from_path`] and [`Template::render`].
431///
432/// # Examples
433///
434/// ```no_run
435/// # fn example() -> docx_templating::Result<()> {
436/// let rendered = docx_templating::render(
437///     "template.docx",
438///     serde_json::json!({ "name": "Ada" }),
439/// )?;
440/// rendered.write_to_file("output.docx")?;
441/// # Ok(())
442/// # }
443/// ```
444pub fn render(path: impl AsRef<Path>, context: impl IntoContext) -> Result<RenderedDocument> {
445    Template::from_path(path)?.render(context)
446}
447
448#[cfg(test)]
449mod tests {
450    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
451
452    use super::*;
453    use crate::package::InMemoryPackageSource;
454    use serde_json::json;
455
456    fn make_test_template(logical_text: &str) -> Template<InMemoryPackageSource> {
457        let mut source = InMemoryPackageSource::new();
458
459        // Add required DOCX parts
460        source.add_part(
461            "[Content_Types].xml",
462            br#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"></Types>"#.to_vec(),
463        );
464        source.add_part(
465            "_rels/.rels",
466            br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>"#.to_vec(),
467        );
468
469        // Add document.xml with the template text
470        let doc_xml = format!(
471            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>"#,
472            logical_text
473        );
474        source.add_part("word/document.xml", doc_xml.into_bytes());
475
476        Template::from_source(source).unwrap()
477    }
478
479    /// Read `word/document.xml` back out of a rendered package.
480    fn document_xml(rendered: &RenderedDocument) -> String {
481        use std::io::Cursor;
482        use zip::ZipArchive;
483
484        let cursor = Cursor::new(rendered.as_bytes());
485        let mut archive = ZipArchive::new(cursor).unwrap();
486        let mut doc_file = archive.by_name("word/document.xml").unwrap();
487
488        let mut doc_xml = String::new();
489        std::io::Read::read_to_string(&mut doc_file, &mut doc_xml).unwrap();
490        doc_xml
491    }
492
493    #[test]
494    fn from_source_validates_package() {
495        let source = InMemoryPackageSource::new();
496        let result = Template::from_source(source);
497        assert!(result.is_err());
498    }
499
500    #[test]
501    fn from_source_parses_ast() {
502        let template = make_test_template("Hello {{name}}!");
503        let inline = template.bound.inline();
504        assert_eq!(inline.len(), 1);
505        assert_eq!(inline[0].nodes.len(), 3); // Text, Variable, Text
506    }
507
508    #[test]
509    fn with_options_sets_config() {
510        let template = make_test_template("{{name}}").with_options(
511            TemplateOptions::default()
512                .missing_value_policy(crate::options::MissingValuePolicy::Empty),
513        );
514
515        assert_eq!(
516            template.options.missing_value_policy,
517            crate::options::MissingValuePolicy::Empty
518        );
519    }
520
521    #[test]
522    fn render_replaces_variable() {
523        let template = make_test_template("Hello {{name}}!");
524        let rendered = template.render(json!({"name": "Ada"})).unwrap();
525
526        assert!(document_xml(&rendered).contains("Hello Ada!"));
527    }
528
529    #[test]
530    fn render_accepts_a_borrowed_struct() {
531        #[derive(serde::Serialize)]
532        struct Data {
533            name: &'static str,
534        }
535
536        let template = make_test_template("Hello {{name}}!");
537        let rendered = template.render(&Data { name: "Ada" }).unwrap();
538
539        assert!(document_xml(&rendered).contains("Hello Ada!"));
540    }
541
542    #[test]
543    fn render_handles_missing_with_error_policy() {
544        let template = make_test_template("Hello {{missing}}!");
545        let result = template.render(json!({}));
546        assert!(result.is_err());
547    }
548
549    #[test]
550    fn render_handles_missing_with_empty_policy() {
551        let template = make_test_template("Hello {{missing}}!").with_options(
552            TemplateOptions::default()
553                .missing_value_policy(crate::options::MissingValuePolicy::Empty),
554        );
555
556        let rendered = template.render(json!({})).unwrap();
557
558        assert!(document_xml(&rendered).contains("Hello !"));
559    }
560}