Registry / serialization / docxtpl

docxtpl

JSON →
library0.20.2pypypi✓ verified 24d ago

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.

pip install docxtpl
INSTALL
IMPORT
SIG · DOCXTPL
D
docxtpl
serializationpythonv0.20.2
Install
2.5s avg
Import
310ms
Disk
32MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.20.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.316s · 34MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.5s · import 0.304s · 34MB
32MB installed
● package 32MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

DocxTemplate
from docxtpl import DocxTemplate
InlineImage
from docxtpl import InlineImage
RichText
from docxtpl import RichText
Can also be imported as 'R'.
RichTextParagraph
from docxtpl import RichTextParagraph
Can also be imported as 'RP'.
Mm
from docx.shared import Mm
Used for specifying dimensions (e.g., image width/height). Also 'Inches' and 'Pt' are available.

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)
Debug
Known issues
gotchaJinja2 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.
fix
Use the appropriate `p`, `tr`, `tc`, or `r` prefixed tags for structural control (paragraph, table row, table cell, run). Consult the official documentation for examples on splitting long text or table loops with these tags.
affects: All versions
gotchaRichText 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.
fix
Pre-process `RichText` content in Python. For example, `context = {'my_text': RichText(my_raw_text.lower())}` instead of `{{r my_text|lower }}` in the template.
affects: All versions
gotchaWhen 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.
fix
Place the `{%tr for ... %}` tag in the first cell of the row to be repeated and the `{%tr endfor %}` tag in the last cell of that same row. The documentation provides examples for proper table looping.
affects: All versions
gotchaControlling whitespace when using conditional or loop tags can be tricky. Unwanted spaces might appear if not handled correctly.
fix
Use Jinja2's whitespace control characters `{%-` and `-%}` to strip whitespace around blocks. For explicit spaces at line beginnings or endings in the Word document, use an unbreakable space (Ctrl+Shift+Space in Microsoft Word).
affects: All versions
breakingPrior 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.
fix
Upgrade to `docxtpl` version 0.15.1 or newer to enable reliable multi-rendering with a single `DocxTemplate` object. If upgrading is not possible, ensure all context is provided in a single `render()` call.
affects: < 0.15.1
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'docxtpl'
The 'docxtpl' package is not installed in the Python environment being used, or there is a mismatch between the environment where it was installed and where the script is being run.
fix
Install the package using pip: `pip install docxtpl` or `pip3 install docxtpl`. If using a virtual environment, ensure it is activated before installation.
AttributeError: 'NoneType' object has no attribute 'styles'
This error occurs when attempting to access attributes of the underlying `python-docx` document object (like `styles`, `paragraphs`, or `tables`) before `docxtpl` has fully loaded or rendered the document, which initializes the `self.docx` attribute.
fix
Ensure that `doc.get_docx()` or `doc.render(context)` has been called before trying to access attributes of the `doc` object that rely on the loaded `python-docx` document. For example, call `doc.get_docx()` explicitly if you need to inspect document properties before rendering.
jinja2.exceptions.TemplateSyntaxError: unexpected char '}'
This typically indicates a malformed Jinja2 tag within the `.docx` template, often due to typos, incorrect nesting of delimiters, or Microsoft Word's auto-formatting introducing hidden characters or breaking the tag structure.
fix
Carefully inspect the Jinja2 tags in your `.docx` template for typos, missing or extra curly braces/percent signs, or other unexpected characters. Retyping the tags directly into Word, ensuring they are correctly delimited, and checking Word's hidden formatting can often resolve this. Ensure complex tags like `{%p %}` are on their own line.
Word found unreadable content in [filename]. Do you want to recover the contents of this document?
The generated `.docx` file is corrupted or contains XML that Microsoft Word (or other document readers like LibreOffice) cannot parse correctly. This is frequently linked to improper handling of images (e.g., too many images with the same ID, incorrect paths, or corrupted image files) or a mismatch in how Word versions interpret the generated document's internal structure.
fix
Review how images are embedded using `docxtpl.InlineImage`, ensuring image paths are correct and that if the same image is used multiple times, `docxtpl` is allowed to generate unique IDs if necessary. Sometimes, opening the *template* document in Word and re-saving it, or saving it as an RTF file and then back to DOCX, can clean up hidden issues that cause problems during `docxtpl` processing.
Table rendering issues (e.g., all data appears in one cell instead of separate rows/columns when using {%tr %} or {%tc %})
Incorrect placement or syntax of `{%tr %}` (for table rows) or `{%tc %}` (for table columns) tags within the Word template. These special tags must typically be the *only* content within their respective table cells to properly define the loop for dynamic row or column generation. Improper variable access (e.g., `{{ item }}` instead of `{{ item.key }}` for dictionary items in a loop) is also a common cause.
fix
Ensure that `{%tr for item in my_list %}` and `{% endtr %}` (or `{%tc %}`/`{% endtc %}`) tags are correctly placed as the sole content within the table cells that define the repeating row or column. Access elements within the loop using the correct dictionary key or attribute, e.g., `{{ item.parameter }}` if `item` is a dictionary.
Upgrade
Version history
0.20.2latest on PyPI · released Nov 13, 2025
Audit
Dependencies
jinja2requiredUsed for the templating syntax within the .docx documents.
lxmlrequiredRequired for XML parsing of .docx files.
python-docxrequiredCore library for reading, writing, and creating Word documents and sub-documents.
subdocoptionalExtra dependency required for advanced sub-document features. Install with 'pip install "docxtpl[subdoc]"'.
Agent activity
42 hits · last 30 days
node
40
Resources
docxtpl — pip install docxtpl · libregistry