docx-templating 1.0.0

Rust library for DOCX templating with variable replacement, conditionals, and loops
Documentation
//! Template rendering options and policies.

use serde_json::Value;

use crate::filters::{FilterError, FilterRegistry};

/// Policy for handling missing values during rendering.
///
/// Controls what happens when a variable path (e.g., `{{user.missing}}`)
/// resolves to `None` in the context.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingValuePolicy {
    /// Return an error when a variable is missing.
    ///
    /// This is the default behavior, providing fail-fast validation
    /// that all required template variables are present in the context.
    Error,

    /// Replace missing variables with empty string.
    ///
    /// Use when optional variables should render as blank text
    /// rather than failing the entire render operation.
    Empty,

    /// Keep the original placeholder text.
    ///
    /// Use when you want to preserve `{{variable}}` syntax in the output
    /// for variables that are not found in the context.
    KeepPlaceholder,
}

/// Policy for handling newline characters (`\n`, `\r\n`) in resolved variable values.
///
/// DOCX ignores literal newline characters inside `<w:t>` elements. This policy
/// controls how the render layer converts them into visible line breaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineBreakPolicy {
    /// Insert a Word soft line break (`<w:br w:type="textWrapping"/>`) between
    /// each line segment.
    ///
    /// All segments stay within the same `<w:p>` and `<w:r>`. This is the
    /// default because it requires no structural changes to the paragraph.
    #[default]
    InsertWordBreak,

    /// Split the containing `<w:p>` into N separate paragraphs — one per line
    /// segment — each inheriting the `<w:pPr>` and `<w:rPr>` of the original.
    ///
    /// Use when downstream consumers need true paragraph boundaries, e.g. for
    /// independent paragraph formatting or mail-merge scenarios.
    SplitParagraph,
}

/// Configuration options for template rendering.
///
/// # Examples
///
/// ```
/// use docx_templating::{TemplateOptions, MissingValuePolicy, LineBreakPolicy};
///
/// let options = TemplateOptions::default()
///     .missing_value_policy(MissingValuePolicy::Empty)
///     .line_break_policy(LineBreakPolicy::SplitParagraph)
///     .preserve_whitespace(false);
/// ```
#[derive(Debug, Clone)]
pub struct TemplateOptions {
    /// Policy for missing variables.
    pub missing_value_policy: MissingValuePolicy,
    /// Policy for newline characters in resolved values.
    pub line_break_policy: LineBreakPolicy,
    /// Whether to emit `xml:space="preserve"` on `<w:t>` elements whose
    /// replacement text has leading or trailing whitespace.
    ///
    /// When `true` (the default) the rewriter adds the attribute automatically
    /// so Word does not strip significant spaces from the rendered value.
    /// Set to `false` to suppress the attribute entirely, letting Word apply
    /// its own whitespace-normalisation rules.
    pub preserve_whitespace: bool,
    /// Whether headers and footers are templated.
    ///
    /// When `false` (the default) `word/header*.xml` and `word/footer*.xml`
    /// are copied into the output unchanged, so a placeholder in a header
    /// stays as written.
    pub headers_and_footers: bool,
    /// Whether footnotes and endnotes are templated.
    ///
    /// When `false` (the default) `word/footnotes.xml` and
    /// `word/endnotes.xml` are copied into the output unchanged.
    pub footnotes: bool,
    /// Filters available to the template.
    ///
    /// Starts with the built in text filters `upper`, `lower`, `trim`,
    /// `default`, `len` and `join` and the number filters `round`, `fixed`,
    /// `thousands` and `percent`. The `dates` feature also adds `date` and
    /// `timezone`. Add or replace a filter with [`TemplateOptions::filter`].
    pub filters: FilterRegistry,
}

impl TemplateOptions {
    /// Set the missing value policy.
    #[must_use]
    pub fn missing_value_policy(mut self, policy: MissingValuePolicy) -> Self {
        self.missing_value_policy = policy;
        self
    }

    /// Set the line break policy.
    #[must_use]
    pub fn line_break_policy(mut self, policy: LineBreakPolicy) -> Self {
        self.line_break_policy = policy;
        self
    }

    /// Set whether to preserve edge whitespace in replacement values.
    ///
    /// When `true` (the default) the rewriter emits `xml:space="preserve"` on
    /// `<w:t>` elements whose replacement text starts or ends with whitespace,
    /// preventing Word from stripping those spaces. Set to `false` to suppress
    /// the attribute and let Word normalise whitespace itself.
    #[must_use]
    pub fn preserve_whitespace(mut self, preserve: bool) -> Self {
        self.preserve_whitespace = preserve;
        self
    }

    /// Set whether headers and footers are templated.
    ///
    /// Disabled by default. Enable it when the template puts placeholders in
    /// a header or a footer.
    ///
    /// # Examples
    ///
    /// ```
    /// use docx_templating::TemplateOptions;
    ///
    /// let options = TemplateOptions::default().headers_and_footers(true);
    /// assert!(options.headers_and_footers);
    /// ```
    #[must_use]
    pub fn headers_and_footers(mut self, process: bool) -> Self {
        self.headers_and_footers = process;
        self
    }

    /// Set whether footnotes and endnotes are templated.
    ///
    /// Disabled by default. Enable it when the template puts placeholders in
    /// a footnote or an endnote.
    ///
    /// # Examples
    ///
    /// ```
    /// use docx_templating::TemplateOptions;
    ///
    /// let options = TemplateOptions::default().footnotes(true);
    /// assert!(options.footnotes);
    /// ```
    #[must_use]
    pub fn footnotes(mut self, process: bool) -> Self {
        self.footnotes = process;
        self
    }

    /// Register a filter for `{{value | name}}` and `{{value | name: "arg"}}`.
    ///
    /// A filter registered here replaces a built in filter with the same name.
    /// The closure receives the current value and the optional argument written
    /// after a colon, and returns the value for the next filter in the chain.
    ///
    /// # Examples
    ///
    /// ```
    /// use docx_templating::{FilterError, TemplateOptions};
    /// use serde_json::Value;
    ///
    /// let options = TemplateOptions::default().filter("shout", |value, _| {
    ///     let text = value
    ///         .as_str()
    ///         .ok_or_else(|| FilterError::new("value is not a string"))?;
    ///     Ok(Value::String(format!("{}!", text.to_uppercase())))
    /// });
    ///
    /// assert!(options.filters.contains("shout"));
    /// ```
    #[must_use]
    pub fn filter<F>(mut self, name: impl Into<String>, filter: F) -> Self
    where
        F: Fn(&Value, Option<&str>) -> Result<Value, FilterError> + Send + Sync + 'static,
    {
        self.filters.insert(name, filter);
        self
    }
}

impl Default for TemplateOptions {
    fn default() -> Self {
        Self {
            missing_value_policy: MissingValuePolicy::Error,
            line_break_policy: LineBreakPolicy::default(),
            preserve_whitespace: true,
            headers_and_footers: false,
            footnotes: false,
            filters: FilterRegistry::default(),
        }
    }
}

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

    use super::*;

    #[test]
    fn default_missing_policy_is_error() {
        assert_eq!(
            TemplateOptions::default().missing_value_policy,
            MissingValuePolicy::Error
        );
    }

    #[test]
    fn default_line_break_policy_is_insert_word_break() {
        assert_eq!(
            TemplateOptions::default().line_break_policy,
            LineBreakPolicy::InsertWordBreak,
        );
    }

    #[test]
    fn builder_sets_missing_policy() {
        let opts = TemplateOptions::default().missing_value_policy(MissingValuePolicy::Empty);
        assert_eq!(opts.missing_value_policy, MissingValuePolicy::Empty);
    }

    #[test]
    fn builder_sets_line_break_policy() {
        let opts = TemplateOptions::default().line_break_policy(LineBreakPolicy::SplitParagraph);
        assert_eq!(opts.line_break_policy, LineBreakPolicy::SplitParagraph);
    }

    #[test]
    fn builder_is_composable() {
        let opts = TemplateOptions::default()
            .missing_value_policy(MissingValuePolicy::Empty)
            .line_break_policy(LineBreakPolicy::SplitParagraph);
        assert_eq!(opts.missing_value_policy, MissingValuePolicy::Empty);
        assert_eq!(opts.line_break_policy, LineBreakPolicy::SplitParagraph);
    }

    #[test]
    fn default_preserve_whitespace_is_true() {
        assert!(TemplateOptions::default().preserve_whitespace);
    }

    #[test]
    fn builder_sets_preserve_whitespace_false() {
        let opts = TemplateOptions::default().preserve_whitespace(false);
        assert!(!opts.preserve_whitespace);
    }

    #[test]
    fn builder_preserve_whitespace_true_is_explicit_set() {
        let opts = TemplateOptions::default().preserve_whitespace(true);
        assert!(opts.preserve_whitespace);
    }

    #[test]
    fn secondary_parts_are_off_by_default() {
        let opts = TemplateOptions::default();
        assert!(!opts.headers_and_footers);
        assert!(!opts.footnotes);
    }

    #[test]
    fn builder_enables_secondary_parts() {
        let opts = TemplateOptions::default()
            .headers_and_footers(true)
            .footnotes(true);
        assert!(opts.headers_and_footers);
        assert!(opts.footnotes);
    }

    #[test]
    fn default_options_carry_the_builtin_filters() {
        let opts = TemplateOptions::default();
        for name in [
            "upper",
            "lower",
            "trim",
            "default",
            "len",
            "join",
            "round",
            "fixed",
            "thousands",
            "percent",
        ] {
            assert!(opts.filters.contains(name), "{name}");
        }
        #[cfg(feature = "dates")]
        for name in ["date", "timezone"] {
            assert!(opts.filters.contains(name), "{name}");
        }
    }

    #[test]
    fn builder_registers_a_filter() {
        let opts = TemplateOptions::default()
            .filter("shout", |value, _| Ok(Value::String(format!("{value}!"))));
        assert!(opts.filters.contains("shout"));
    }
}