or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdmedia-composition.mdrich-text.mdtemplate-processing.md
tile.json

tessl/pypi-docxtpl

Use a docx as a jinja2 template

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/docxtpl@0.20.x

To install, run

npx @tessl/cli install tessl/pypi-docxtpl@0.20.0

index.mddocs/

DocxTpl

A 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.

Package Information

  • Package Name: docxtpl
  • Language: Python
  • Installation: pip install docxtpl
  • Dependencies: python-docx>=1.1.1, docxcompose, jinja2, lxml

Core Imports

from docxtpl import DocxTemplate

Complete 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
)

Basic Usage

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.docx

CLI options:

  • -o, --overwrite: Overwrite output file without confirmation if it exists
  • -q, --quiet: Do not display unnecessary messages
  • -h, --help: Show help message and exit

Architecture

DocxTpl's architecture centers around the DocxTemplate class that orchestrates:

  • Template Processing: Jinja2 integration for variables, loops, and conditionals in Word documents
  • Rich Content: Specialized classes for formatted text, images, and complex document elements
  • Document Structure: Support for headers, footers, tables, and document composition
  • Media Management: Intelligent handling of images and embedded objects with replacement capabilities

The design allows Word documents to serve as visual templates while maintaining programmatic control over content generation.

Capabilities

Core Template Processing

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: ...

Core Template Processing

Rich Text Formatting

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): ...

Rich Text Formatting

Media and Document Composition

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

Types

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]