docxtpl
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
- gotcha Jinja2 tag placement is crucial. Standard `{{ }}` tags must reside within a single 'run' of text in a paragraph. For controlling entire paragraphs, table rows, or cells, special tags like `{%p ... %}`, `{%tr ... %}`, `{%tc ... %}` respectively are required. Incorrect placement often leads to unexpected rendering or content being crammed.
- gotcha RichText objects are not compatible with Jinja2 filters directly within the template. If you need to apply formatting or transformations to `RichText` content, perform these operations in your Python code *before* passing the `RichText` object to the template context.
- gotcha When working with loops in tables (`{%tr for item in items %}`), ensure the loop tags correctly span the cells of the row you intend to duplicate. Incorrect placement can cause all iterated data to appear in a single cell instead of generating new rows.
- gotcha Controlling whitespace when using conditional or loop tags can be tricky. Unwanted spaces might appear if not handled correctly.
- breaking Prior to version 0.15.1, calling `render()` multiple times on the same `DocxTemplate` object could lead to loss of unresolved variables, making multi-step rendering problematic.
Install
-
pip install docxtpl -
conda install docxtpl --channel conda-forge
Imports
- DocxTemplate
from docxtpl import DocxTemplate
- InlineImage
from docxtpl import InlineImage
- RichText
from docxtpl import RichText
- RichTextParagraph
from docxtpl import RichTextParagraph
- Mm
from docx.shared import Mm
Quickstart
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)