docxtpl

0.20.2 · active · verified Sat Apr 11

docxtpl is a Python library that serves as a docx template engine, enabling the generation of Word documents from templates enhanced with Jinja2-like tags. It leverages `python-docx` for document manipulation and `jinja2` for templating logic. The current version is 0.20.2, and it appears to be actively maintained with regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a .docx template, provide a dictionary of context variables, render the template, and save the generated document. The template itself would be a standard .docx file created in Microsoft Word, containing Jinja2-like placeholders such as `{{ variable_name }}`.

import os
from docxtpl import DocxTemplate

# Create a dummy template file for demonstration
dummy_template_content = (
    "Hello {{ name }},\n"
    "This is a test document generated by docxtpl.\n"
    "Your company: {{ company_name }}.\n"
)
with open("my_word_template.docx", "w") as f:
    # In a real scenario, this would be a proper .docx file with Jinja2 tags
    # For a runnable quickstart, we'll simulate a simple text file
    f.write(dummy_template_content)

# Path to your Word template file (e.g., 'my_word_template.docx')
template_path = "my_word_template.docx"
output_path = "generated_doc.docx"

# Ensure the template file exists (in a real scenario, it's a pre-made .docx)
if not os.path.exists(template_path):
    # For a real .docx, you would create it in MS Word
    print(f"Please create a real .docx template named '{template_path}' with {{ name }} and {{ company_name }} tags.")
    # Exit or handle error if the template doesn't exist
    exit(1)

# Load the template
doc = DocxTemplate(template_path)

# Define the context (data to fill into the template)
context = {
    'name': 'World',
    'company_name': 'Example Inc.'
}

# Render the document with the context
doc.render(context)

# Save the generated document
doc.save(output_path)

print(f"Generated document saved to {output_path}")

# Clean up the dummy file (optional)
# os.remove(template_path)
# os.remove(output_path)

view raw JSON →