CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-docxtpl

Use a docx as a jinja2 template

Pending
Overview
Eval results
Files

template-processing.mddocs/

Core Template Processing

Main functionality for loading Word documents as templates, rendering them with context data, and managing the template lifecycle. The DocxTemplate class provides the primary interface for all template operations.

Capabilities

DocxTemplate Class

The main class for managing docx files as Jinja2 templates. Handles document loading, template rendering, and output generation.

class DocxTemplate:
    def __init__(self, template_file: Union[IO[bytes], str, os.PathLike]) -> None:
        """
        Initialize DocxTemplate with a template file.
        
        Parameters:
        - template_file: Path to docx template file or file-like object
        """

Template Rendering

Core method for processing templates with context data using Jinja2 template engine.

def render(self, context: Dict[str, Any], jinja_env: Optional[Environment] = None, autoescape: bool = False) -> None:
    """
    Render the template with provided context data.
    
    Parameters:
    - context: Dictionary containing template variables and data
    - jinja_env: Optional custom Jinja2 environment for template processing
    - autoescape: Enable HTML/XML autoescape in Jinja2 processing
    """

Document Output

Methods for saving rendered documents to files or file-like objects.

def save(self, filename: Union[IO[bytes], str, os.PathLike], *args, **kwargs) -> None:
    """
    Save the rendered document to file.
    
    Parameters:
    - filename: Output file path or file-like object
    - *args, **kwargs: Additional arguments passed to python-docx save method
    """

Subdocument Creation

Create new subdocuments for complex document composition scenarios.

def new_subdoc(self, docpath=None):
    """
    Create a new subdocument for insertion into the main template.
    
    Parameters:
    - docpath: Optional path to existing document to use as subdocument base
    
    Returns:
    Subdoc: New subdocument instance
    """

Media Replacement

Methods for replacing media files, images, and embedded objects within templates.

def replace_media(self, src_file, dst_file):
    """
    Replace media file in template by filename.
    
    Parameters:
    - src_file: Source filename in template
    - dst_file: Replacement file path
    """

def replace_pic(self, embedded_file, dst_file):
    """
    Replace embedded picture by filename.
    
    Parameters:
    - embedded_file: Embedded picture filename
    - dst_file: Replacement image file path
    """

def replace_embedded(self, src_file, dst_file):
    """
    Replace embedded object by filename.
    
    Parameters:
    - src_file: Source embedded object filename
    - dst_file: Replacement file path
    """

def replace_zipname(self, zipname, dst_file):
    """
    Replace file by ZIP archive path.
    
    Parameters:
    - zipname: ZIP path within docx archive
    - dst_file: Replacement file path
    """

Replacement Management

Methods for managing and resetting media replacement operations.

def reset_replacements(self):
    """
    Reset all replacement dictionaries to empty state.
    """

URL and Link Handling

Utilities for managing hyperlinks and URL references within templates.

def build_url_id(self, url):
    """
    Build URL ID for hyperlink references.
    
    Parameters:
    - url: URL string to process
    
    Returns:
    str: Generated URL ID for hyperlink reference
    """

Template Analysis

Tools for analyzing template variables and validation.

def get_undeclared_template_variables(self, jinja_env: Optional[Environment] = None, context: Optional[Dict[str, Any]] = None) -> Set[str]:
    """
    Get template variables that are not declared in the provided context.
    
    Parameters:
    - jinja_env: Optional custom Jinja2 environment
    - context: Optional context dictionary to check against
    
    Returns:
    set: Set of undeclared variable names
    """

Properties

Access to template state and underlying document objects.

@property
def docx:
    """
    Access to underlying python-docx Document object.
    
    Returns:
    Document: python-docx Document instance
    """

@property
def template_file:
    """
    Template file path or object.
    
    Returns:
    Union[str, PathLike, IO]: Original template file reference
    """

@property
def is_rendered(self) -> bool:
    """
    Boolean flag indicating if template has been rendered.
    
    Returns:
    bool: True if render() has been called
    """

@property
def is_saved(self) -> bool:
    """
    Boolean flag indicating if document has been saved.
    
    Returns:
    bool: True if save() has been called
    """

@property
def allow_missing_pics(self) -> bool:
    """
    Boolean flag for allowing missing pictures in template.
    
    Returns:
    bool: Current setting for missing picture handling
    """

Constants

Class constants for document relationship URIs.

HEADER_URI: str  # URI for header relationships
FOOTER_URI: str  # URI for footer relationships

Usage Examples

Basic Template Processing

from docxtpl import DocxTemplate

# Load template
doc = DocxTemplate("invoice_template.docx")

# Prepare data
context = {
    'customer_name': 'John Doe',
    'invoice_number': 'INV-001',
    'items': [
        {'description': 'Consulting', 'amount': 1000},
        {'description': 'Development', 'amount': 2000}
    ],
    'total': 3000
}

# Render and save
doc.render(context)
doc.save("invoice_001.docx")

Custom Jinja2 Environment

from jinja2 import Environment
from docxtpl import DocxTemplate

# Create custom Jinja2 environment
jinja_env = Environment()
jinja_env.filters['currency'] = lambda x: f"${x:,.2f}"

# Use with template
doc = DocxTemplate("financial_report.docx")
context = {'revenue': 150000, 'expenses': 120000}
doc.render(context, jinja_env=jinja_env)
doc.save("report.docx")

Template Variable Validation

from docxtpl import DocxTemplate

doc = DocxTemplate("template.docx")
context = {'name': 'John', 'age': 30}

# Check for missing variables
missing_vars = doc.get_undeclared_template_variables(context=context)
if missing_vars:
    print(f"Missing template variables: {missing_vars}")
else:
    doc.render(context)
    doc.save("output.docx")

Install with Tessl CLI

npx tessl i tessl/pypi-docxtpl

docs

index.md

media-composition.md

rich-text.md

template-processing.md

tile.json