Skip to main content

docx_templating/
options.rs

1//! Template rendering options and policies.
2
3use serde_json::Value;
4
5use crate::filters::{FilterError, FilterRegistry};
6
7/// Policy for handling missing values during rendering.
8///
9/// Controls what happens when a variable path (e.g., `{{user.missing}}`)
10/// resolves to `None` in the context.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum MissingValuePolicy {
13    /// Return an error when a variable is missing.
14    ///
15    /// This is the default behavior, providing fail-fast validation
16    /// that all required template variables are present in the context.
17    Error,
18
19    /// Replace missing variables with empty string.
20    ///
21    /// Use when optional variables should render as blank text
22    /// rather than failing the entire render operation.
23    Empty,
24
25    /// Keep the original placeholder text.
26    ///
27    /// Use when you want to preserve `{{variable}}` syntax in the output
28    /// for variables that are not found in the context.
29    KeepPlaceholder,
30}
31
32/// Policy for handling newline characters (`\n`, `\r\n`) in resolved variable values.
33///
34/// DOCX ignores literal newline characters inside `<w:t>` elements. This policy
35/// controls how the render layer converts them into visible line breaks.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub enum LineBreakPolicy {
38    /// Insert a Word soft line break (`<w:br w:type="textWrapping"/>`) between
39    /// each line segment.
40    ///
41    /// All segments stay within the same `<w:p>` and `<w:r>`. This is the
42    /// default because it requires no structural changes to the paragraph.
43    #[default]
44    InsertWordBreak,
45
46    /// Split the containing `<w:p>` into N separate paragraphs — one per line
47    /// segment — each inheriting the `<w:pPr>` and `<w:rPr>` of the original.
48    ///
49    /// Use when downstream consumers need true paragraph boundaries, e.g. for
50    /// independent paragraph formatting or mail-merge scenarios.
51    SplitParagraph,
52}
53
54/// Configuration options for template rendering.
55///
56/// # Examples
57///
58/// ```
59/// use docx_templating::{TemplateOptions, MissingValuePolicy, LineBreakPolicy};
60///
61/// let options = TemplateOptions::default()
62///     .missing_value_policy(MissingValuePolicy::Empty)
63///     .line_break_policy(LineBreakPolicy::SplitParagraph)
64///     .preserve_whitespace(false);
65/// ```
66#[derive(Debug, Clone)]
67pub struct TemplateOptions {
68    /// Policy for missing variables.
69    pub missing_value_policy: MissingValuePolicy,
70    /// Policy for newline characters in resolved values.
71    pub line_break_policy: LineBreakPolicy,
72    /// Whether to emit `xml:space="preserve"` on `<w:t>` elements whose
73    /// replacement text has leading or trailing whitespace.
74    ///
75    /// When `true` (the default) the rewriter adds the attribute automatically
76    /// so Word does not strip significant spaces from the rendered value.
77    /// Set to `false` to suppress the attribute entirely, letting Word apply
78    /// its own whitespace-normalisation rules.
79    pub preserve_whitespace: bool,
80    /// Whether headers and footers are templated.
81    ///
82    /// When `false` (the default) `word/header*.xml` and `word/footer*.xml`
83    /// are copied into the output unchanged, so a placeholder in a header
84    /// stays as written.
85    pub headers_and_footers: bool,
86    /// Whether footnotes and endnotes are templated.
87    ///
88    /// When `false` (the default) `word/footnotes.xml` and
89    /// `word/endnotes.xml` are copied into the output unchanged.
90    pub footnotes: bool,
91    /// Filters available to the template.
92    ///
93    /// Starts with the built in text filters `upper`, `lower`, `trim`,
94    /// `default`, `len` and `join` and the number filters `round`, `fixed`,
95    /// `thousands` and `percent`. The `dates` feature also adds `date` and
96    /// `timezone`. Add or replace a filter with [`TemplateOptions::filter`].
97    pub filters: FilterRegistry,
98}
99
100impl TemplateOptions {
101    /// Set the missing value policy.
102    #[must_use]
103    pub fn missing_value_policy(mut self, policy: MissingValuePolicy) -> Self {
104        self.missing_value_policy = policy;
105        self
106    }
107
108    /// Set the line break policy.
109    #[must_use]
110    pub fn line_break_policy(mut self, policy: LineBreakPolicy) -> Self {
111        self.line_break_policy = policy;
112        self
113    }
114
115    /// Set whether to preserve edge whitespace in replacement values.
116    ///
117    /// When `true` (the default) the rewriter emits `xml:space="preserve"` on
118    /// `<w:t>` elements whose replacement text starts or ends with whitespace,
119    /// preventing Word from stripping those spaces. Set to `false` to suppress
120    /// the attribute and let Word normalise whitespace itself.
121    #[must_use]
122    pub fn preserve_whitespace(mut self, preserve: bool) -> Self {
123        self.preserve_whitespace = preserve;
124        self
125    }
126
127    /// Set whether headers and footers are templated.
128    ///
129    /// Disabled by default. Enable it when the template puts placeholders in
130    /// a header or a footer.
131    ///
132    /// # Examples
133    ///
134    /// ```
135    /// use docx_templating::TemplateOptions;
136    ///
137    /// let options = TemplateOptions::default().headers_and_footers(true);
138    /// assert!(options.headers_and_footers);
139    /// ```
140    #[must_use]
141    pub fn headers_and_footers(mut self, process: bool) -> Self {
142        self.headers_and_footers = process;
143        self
144    }
145
146    /// Set whether footnotes and endnotes are templated.
147    ///
148    /// Disabled by default. Enable it when the template puts placeholders in
149    /// a footnote or an endnote.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use docx_templating::TemplateOptions;
155    ///
156    /// let options = TemplateOptions::default().footnotes(true);
157    /// assert!(options.footnotes);
158    /// ```
159    #[must_use]
160    pub fn footnotes(mut self, process: bool) -> Self {
161        self.footnotes = process;
162        self
163    }
164
165    /// Register a filter for `{{value | name}}` and `{{value | name: "arg"}}`.
166    ///
167    /// A filter registered here replaces a built in filter with the same name.
168    /// The closure receives the current value and the optional argument written
169    /// after a colon, and returns the value for the next filter in the chain.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use docx_templating::{FilterError, TemplateOptions};
175    /// use serde_json::Value;
176    ///
177    /// let options = TemplateOptions::default().filter("shout", |value, _| {
178    ///     let text = value
179    ///         .as_str()
180    ///         .ok_or_else(|| FilterError::new("value is not a string"))?;
181    ///     Ok(Value::String(format!("{}!", text.to_uppercase())))
182    /// });
183    ///
184    /// assert!(options.filters.contains("shout"));
185    /// ```
186    #[must_use]
187    pub fn filter<F>(mut self, name: impl Into<String>, filter: F) -> Self
188    where
189        F: Fn(&Value, Option<&str>) -> Result<Value, FilterError> + Send + Sync + 'static,
190    {
191        self.filters.insert(name, filter);
192        self
193    }
194}
195
196impl Default for TemplateOptions {
197    fn default() -> Self {
198        Self {
199            missing_value_policy: MissingValuePolicy::Error,
200            line_break_policy: LineBreakPolicy::default(),
201            preserve_whitespace: true,
202            headers_and_footers: false,
203            footnotes: false,
204            filters: FilterRegistry::default(),
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
212
213    use super::*;
214
215    #[test]
216    fn default_missing_policy_is_error() {
217        assert_eq!(
218            TemplateOptions::default().missing_value_policy,
219            MissingValuePolicy::Error
220        );
221    }
222
223    #[test]
224    fn default_line_break_policy_is_insert_word_break() {
225        assert_eq!(
226            TemplateOptions::default().line_break_policy,
227            LineBreakPolicy::InsertWordBreak,
228        );
229    }
230
231    #[test]
232    fn builder_sets_missing_policy() {
233        let opts = TemplateOptions::default().missing_value_policy(MissingValuePolicy::Empty);
234        assert_eq!(opts.missing_value_policy, MissingValuePolicy::Empty);
235    }
236
237    #[test]
238    fn builder_sets_line_break_policy() {
239        let opts = TemplateOptions::default().line_break_policy(LineBreakPolicy::SplitParagraph);
240        assert_eq!(opts.line_break_policy, LineBreakPolicy::SplitParagraph);
241    }
242
243    #[test]
244    fn builder_is_composable() {
245        let opts = TemplateOptions::default()
246            .missing_value_policy(MissingValuePolicy::Empty)
247            .line_break_policy(LineBreakPolicy::SplitParagraph);
248        assert_eq!(opts.missing_value_policy, MissingValuePolicy::Empty);
249        assert_eq!(opts.line_break_policy, LineBreakPolicy::SplitParagraph);
250    }
251
252    #[test]
253    fn default_preserve_whitespace_is_true() {
254        assert!(TemplateOptions::default().preserve_whitespace);
255    }
256
257    #[test]
258    fn builder_sets_preserve_whitespace_false() {
259        let opts = TemplateOptions::default().preserve_whitespace(false);
260        assert!(!opts.preserve_whitespace);
261    }
262
263    #[test]
264    fn builder_preserve_whitespace_true_is_explicit_set() {
265        let opts = TemplateOptions::default().preserve_whitespace(true);
266        assert!(opts.preserve_whitespace);
267    }
268
269    #[test]
270    fn secondary_parts_are_off_by_default() {
271        let opts = TemplateOptions::default();
272        assert!(!opts.headers_and_footers);
273        assert!(!opts.footnotes);
274    }
275
276    #[test]
277    fn builder_enables_secondary_parts() {
278        let opts = TemplateOptions::default()
279            .headers_and_footers(true)
280            .footnotes(true);
281        assert!(opts.headers_and_footers);
282        assert!(opts.footnotes);
283    }
284
285    #[test]
286    fn default_options_carry_the_builtin_filters() {
287        let opts = TemplateOptions::default();
288        for name in [
289            "upper",
290            "lower",
291            "trim",
292            "default",
293            "len",
294            "join",
295            "round",
296            "fixed",
297            "thousands",
298            "percent",
299        ] {
300            assert!(opts.filters.contains(name), "{name}");
301        }
302        #[cfg(feature = "dates")]
303        for name in ["date", "timezone"] {
304            assert!(opts.filters.contains(name), "{name}");
305        }
306    }
307
308    #[test]
309    fn builder_registers_a_filter() {
310        let opts = TemplateOptions::default()
311            .filter("shout", |value, _| Ok(Value::String(format!("{value}!"))));
312        assert!(opts.filters.contains("shout"));
313    }
314}