Ootempl.Template (ootempl v0.3.0)

Represents a pre-loaded and parsed .docx template optimized for batch rendering.

This module provides a performance optimization for scenarios where the same template is used to generate multiple documents with different data. Instead of re-reading and re-parsing the template file for each render operation, you can load the template once and reuse it multiple times.

Performance Benefits

Loading a template extracts, parses, and normalizes all XML files from the .docx archive. This eliminates approximately 40% of the rendering time for batch operations:

  • File I/O: ~20% of render time
  • XML parsing: ~18% of render time
  • Normalization: ~0.2% of render time

Usage

Batch Processing (Optimized)

# Load template once
{:ok, template} = Ootempl.load("invoice_template.docx")

# Render multiple documents (fast - no I/O or parsing)
Enum.each(customers, fn customer ->
  data = %{"name" => customer.name, "total" => customer.balance}
  Ootempl.render(template, data, "invoice_#{customer.id}.docx")
end)

Single Document (Convenience)

# One-shot rendering (does everything in one call)
Ootempl.render("template.docx", data, "output.docx")

Structure

The Template struct contains all parsed and normalized XML structures from the .docx template, ready to be cloned and processed for each render operation.

Summary

Functions

Deep clones an XML element structure.

Clones a map of XML elements (for headers/footers).

Creates a new Template struct.

Types

t()

@type t() :: %Ootempl.Template{
  app_properties: Ootempl.Xml.xml_element() | nil,
  core_properties: Ootempl.Xml.xml_element() | nil,
  document: Ootempl.Xml.xml_element(),
  endnotes: Ootempl.Xml.xml_element() | nil,
  footers: %{required(String.t()) => Ootempl.Xml.xml_element()},
  footnotes: Ootempl.Xml.xml_element() | nil,
  headers: %{required(String.t()) => Ootempl.Xml.xml_element()},
  source_path: String.t() | nil,
  static_files: %{required(String.t()) => binary()}
}

Functions

clone_xml(element)

Deep clones an XML element structure.

Required because XML elements are modified during rendering, so each render operation needs its own copy of the template's XML structure.

clone_xml_map(xml_map)

@spec clone_xml_map(%{required(String.t()) => Ootempl.Xml.xml_element()}) :: %{
  required(String.t()) => Ootempl.Xml.xml_element()
}

Clones a map of XML elements (for headers/footers).

new(attrs)

@spec new(keyword()) :: t()

Creates a new Template struct.

This is typically called by Ootempl.load/1 rather than directly.