Skip to content

Template preflight and rendering

"""Check the template before rendering: both formats."""
from pathlib import Path
from pywpdoc import Document


def run(fmt: str, out_dir: Path) -> Path:
    out_dir.mkdir(parents=True, exist_ok=True)
    doc = Document.new(fmt)
    doc.add_paragraph("Customer: {{customer.name}}")
    data = {"customer": {"name": "Rydolabs"}}
    report = doc.check_template(data)
    assert report.ok and report.tag_count == 1
    assert doc.render_template(data) == 1
    path = out_dir / f"template.{fmt}"
    doc.save(path)
    assert "Rydolabs" in Document.open(path).paragraphs[-1].text
    return path


if __name__ == "__main__":
    import sys
    print(run(sys.argv[1], Path(sys.argv[2])))

Run: python examples/manual/template.py docx ./output (also hwpx).

  • check_template(data, *, everywhere=True, sections=False, table_rows=False) is read-only, returning TemplateCheckReport.
  • report.ok, tag_count, missing_keys, missing_count, and issues let you decide whether to render.
  • render_template(data, *, everywhere=True, missing="keep", sections=False, table_rows=False) modifies the document, returning the number of processed substitutions.
  • Section and table-row repetition are more advanced: enable sections=True/table_rows=True only for templates designed for the corresponding syntax. Test real documents before bulk processing.

Run preflight before modifying customer files. For read-only analysis, call only check_template, not render_template.