Use a docx as a jinja2 template
npx @tessl/cli install tessl/pypi-docxtpl@0.20.0A powerful Python library that uses docx files as Jinja2 templates. DocxTpl bridges the gap between python-docx for document manipulation and Jinja2 for template processing, enabling dynamic Word document generation from templates with embedded variables, loops, conditionals, and rich formatting capabilities.
pip install docxtplfrom docxtpl import DocxTemplateComplete imports for all functionality:
from docxtpl import (
DocxTemplate, # Main template class
RichText, R, # Rich text formatting
RichTextParagraph, RP, # Rich text paragraphs
InlineImage, # Image insertion
Subdoc, # Document composition
Listing # Text with special characters
)from docxtpl import DocxTemplate
# Load a Word document as template
doc = DocxTemplate("template.docx")
# Prepare context data
context = {
'company_name': 'Example Corp',
'items': [
{'name': 'Product A', 'price': 100},
{'name': 'Product B', 'price': 200}
]
}
# Render the template with context data
doc.render(context)
# Save the rendered document
doc.save("output.docx")Command-line usage:
python -m docxtpl [-h] [-o] [-q] template.docx data.json output.docxCLI options:
-o, --overwrite: Overwrite output file without confirmation if it exists-q, --quiet: Do not display unnecessary messages-h, --help: Show help message and exitDocxTpl's architecture centers around the DocxTemplate class that orchestrates:
The design allows Word documents to serve as visual templates while maintaining programmatic control over content generation.
Main functionality for loading Word documents as templates, rendering them with context data, and managing the template lifecycle.
class DocxTemplate:
def __init__(self, template_file: Union[IO[bytes], str, os.PathLike]) -> None: ...
def render(self, context: Dict[str, Any], jinja_env: Optional[Environment] = None, autoescape: bool = False) -> None: ...
def save(self, filename: Union[IO[bytes], str, os.PathLike], *args, **kwargs) -> None: ...Advanced text formatting capabilities for creating rich content within templates, including styled text, hyperlinks, and complex paragraph formatting.
class RichText:
def __init__(self, text=None, **text_prop): ...
def add(self, text, style=None, color=None, highlight=None, size=None,
subscript=None, superscript=None, bold=False, italic=False,
underline=False, strike=False, font=None, url_id=None,
rtl=False, lang=None): ...
class RichTextParagraph:
def __init__(self, text=None, **text_prop): ...
def add(self, text, parastyle=None): ...Functionality for inserting images, composing sub-documents, and handling media replacement within templates.
class InlineImage:
def __init__(self, tpl, image_descriptor, width=None, height=None, anchor=None): ...
class Subdoc:
def __init__(self, tpl, docpath=None): ...
class Listing:
def __init__(self, text): ...Media and Document Composition
from typing import Union, Dict, Any, Optional, IO, Set
from os import PathLike
from jinja2 import Environment
# Template file types
TemplateFile = Union[IO[bytes], str, PathLike]
# Context data for template rendering
Context = Dict[str, Any]
# Jinja2 environment for custom template processing
JinjaEnvironment = Optional[Environment]