Home
cd ../playbooks
ProductivityIntermediate

Document Template Engine

Auto-fill document templates with data - mail merge for any format

10 minutes
By communitySource
#template#engine#autofill#docxtpl

You need to generate 200 personalized contracts from a spreadsheet but Word mail merge can't handle your complex template with conditional sections. This playbook auto-fills document templates with data from any source — like mail merge but for any format, with logic, loops, and conditional content.

Who it's for: operations managers generating hundreds of personalized documents from spreadsheet data, legal teams producing customized contracts from client data templates, HR departments automating offer letters and onboarding documents, sales teams creating personalized proposals from CRM data, administrative staff producing certificates, invoices, or reports from data sources

Example

"Generate 150 personalized vendor agreements from our contractor spreadsheet" → Template engine pipeline: template design with placeholder fields and conditional sections, data source connection to spreadsheet or CSV, field mapping between data columns and template variables, batch document generation with per-record customization, and output as individual PDFs or DOCX files named by vendor

CLAUDE.md Template

New here? 3-minute setup guide → | Already set up? Copy the template below.

# Template Engine

## Overview

This workflow enables template-based document generation - define templates with placeholders, then automatically fill them with data. Works with Word, Excel, PowerPoint, and more.

## How to Use

1. Describe what you want to accomplish
2. Provide any required input data or files
3. I'll execute the appropriate operations

**Example prompts:**
- "Mail merge for bulk letters/contracts"
- "Generate personalized reports from data"
- "Create certificates from templates"
- "Auto-fill forms with user data"

## Domain Knowledge


### Template Syntax (Jinja2-based)

```
{{ variable }}           - Simple substitution
{% for item in list %}   - Loop
{% if condition %}       - Conditional
{{ date | format_date }} - Filter
```

### Word Template Example

```python
from docxtpl import DocxTemplate

# Create template with placeholders:
# Dear {{ name }},
# Thank you for your order #{{ order_id }}...

def fill_template(template_path: str, data: dict, output_path: str):
    doc = DocxTemplate(template_path)
    doc.render(data)
    doc.save(output_path)
    return output_path

# Usage
fill_template(
    "templates/order_confirmation.docx",
    {
        "name": "John Smith",
        "order_id": "ORD-12345",
        "items": [
            {"name": "Product A", "qty": 2, "price": 29.99},
            {"name": "Product B", "qty": 1, "price": 49.99}
        ],
        "total": 109.97
    },
    "output/confirmation_john.docx"
)
```

### Excel Template

```python
from openpyxl import load_workbook
import re

def fill_excel_template(template_path: str, data: dict, output_path: str):
    wb = load_workbook(template_path)
    ws = wb.active
    
    # Find and replace placeholders like {{name}}
    for row in ws.iter_rows():
        for cell in row:
            if cell.value and isinstance(cell.value, str):
                for key, value in data.items():
                    placeholder = "{{" + key + "}}"
                    if placeholder in cell.value:
                        cell.value = cell.value.replace(placeholder, str(value))
    
    wb.save(output_path)
    return output_path
```

### Bulk Generation (Mail Merge)

```python
import csv
from pathlib import Path

def mail_merge(template_path: str, data_csv: str, output_dir: str):
    """Generate documents for each row in CSV."""
    
    Path(output_dir).mkdir(exist_ok=True)
    
    with open(data_csv) as f:
        reader = csv.DictReader(f)
        
        for i, row in enumerate(reader):
            output_path = f"{output_dir}/document_{i+1}.docx"
            fill_template(template_path, row, output_path)
            print(f"Generated: {output_path}")

# Usage with contacts.csv:
# name,email,company
# John,john@example.com,Acme
# Jane,jane@example.com,Corp

mail_merge(
    "templates/welcome_letter.docx",
    "data/contacts.csv",
    "output/letters"
)
```

### Advanced: Conditional Content

```python
from docxtpl import DocxTemplate

# Template with conditionals:
# {% if vip %}
# Thank you for being a VIP member!
# {% else %}
# Thank you for your purchase.
# {% endif %}

doc = DocxTemplate("template.docx")
doc.render({
    "name": "John",
    "vip": True,
    "discount": 20
})
doc.save("output.docx")
```


## Best Practices

1. **Use clear placeholder naming ({{client_name}})**
2. **Validate data before rendering**
3. **Handle missing data gracefully**
4. **Keep templates version-controlled**

## Installation

```bash
# Install required dependencies
pip install python-docx openpyxl python-pptx reportlab jinja2
```

## Resources

- [docxtpl / yumdocs Repository](https://github.com/elapouya/python-docxtpl)
- [Claude Code Hub](https://github.com/claude-code/workflows)
README.md

What This Does

This workflow enables template-based document generation - define templates with placeholders, then automatically fill them with data. Works with Word, Excel, PowerPoint, and more.


Quick Start

Step 1: Create a Project Folder

mkdir -p ~/Documents/TemplateEngine

Step 2: Download the Template

Click Download above, then:

mv ~/Downloads/CLAUDE.md ~/Documents/TemplateEngine/

Step 3: Start Working

cd ~/Documents/TemplateEngine
claude

How to Use

  1. Describe what you want to accomplish
  2. Provide any required input data or files
  3. I'll execute the appropriate operations

Example prompts:

  • "Mail merge for bulk letters/contracts"
  • "Generate personalized reports from data"
  • "Create certificates from templates"
  • "Auto-fill forms with user data"

Best Practices

  1. Use clear placeholder naming ({{client_name}})
  2. Validate data before rendering
  3. Handle missing data gracefully
  4. Keep templates version-controlled

Installation

# Install required dependencies
pip install python-docx openpyxl python-pptx reportlab jinja2

$Related Playbooks

Productivity

System Performance Diagnostics

Run comprehensive performance checks to diagnose why your computer is running slow and get prioritized fixes.

5 minutes
Beginner
Productivity

Validate Output

Validate content structure.

15 minutes
Intermediate
Productivity

Verify Claims

Verify marketing claims.

15 minutes
Intermediate
Productivity

Weather-Based Automation

Automate weather-based workflows, forecasts, alerts, and location-aware notifications

10 minutes
Intermediate
Productivity

Voice & Screenshot Workflow

Control Claude Code with voice dictation and automatic screenshot review - almost no typing required.

15 minutes
Intermediate
Productivity

Video Downloader

Download YouTube videos with customizable quality and format settings, including audio extraction to MP3.

5 minutes
Beginner
Productivity

Year-in-Review Generator

Automatically compile your yearly accomplishments from Jira tickets, git history, emails, and documents into a polished summary for performance reviews or personal reflection.

5 minutes
Beginner
Productivity

Travel Planner

Create personalized travel itineraries with day-by-day plans, budget breakdowns, packing lists, and cultural tips based on your preferences.

10 minutes
Beginner
Productivity

Travel Command Center

Centralize your entire trip in one workspace — itinerary, bookings, packing list, and restaurant picks that all reference each other.

5 minutes
Beginner
Productivity

Raffle Winner Picker

Randomly select winners from Google Sheets, CSVs, or lists for giveaways with transparent, verifiable selection.

5 minutes
Beginner
Productivity

Add Integration

Add MCP server integrations.

15 minutes
Intermediate
Productivity

Activity Digest Generator

Generate daily or weekly activity digests across all connected platforms

10 minutes
Beginner

Browse all Productivity playbooks →