template-engine

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Template Engine Skill

模板引擎Skill

Overview

概述

This skill enables template-based document generation - define templates with placeholders, then automatically fill them with data. Works with Word, Excel, PowerPoint, and more.
该Skill支持基于模板的文档生成——定义带有占位符的模板,然后自动用数据填充。适用于Word、Excel、PowerPoint等多种格式。

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"
  1. 描述你想要实现的需求
  2. 提供所需的输入数据或文件
  3. 我会执行相应的操作
示例提示词:
  • "为批量信件/合同执行邮件合并"
  • "根据数据生成个性化报告"
  • "从模板创建证书"
  • "用用户数据自动填充表单"

Domain Knowledge

领域知识

Template Syntax (Jinja2-based)

模板语法(基于Jinja2)

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

Word Template Example

Word模板示例

python
from docxtpl import DocxTemplate
python
from docxtpl import DocxTemplate

Create template with placeholders:

Create template with placeholders:

Dear {{ name }},

Dear {{ name }},

Thank you for your order #{{ order_id }}...

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

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" )
undefined
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" )
undefined

Excel Template

Excel模板

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
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}")
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:

Usage with contacts.csv:

name,email,company

name,email,company

John,john@example.com,Acme

John,john@example.com,Acme

Jane,jane@example.com,Corp

Jane,jane@example.com,Corp

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

Advanced: Conditional Content

进阶:条件内容

python
from docxtpl import DocxTemplate
python
from docxtpl import DocxTemplate

Template with conditionals:

Template with conditionals:

{% if vip %}

{% if vip %}

Thank you for being a VIP member!

Thank you for being a VIP member!

{% else %}

{% else %}

Thank you for your purchase.

Thank you for your purchase.

{% endif %}

{% endif %}

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

Best Practices

最佳实践

  1. Use clear placeholder naming ({{client_name}})
  2. Validate data before rendering
  3. Handle missing data gracefully
  4. Keep templates version-controlled
  1. 使用清晰的占位符命名(如{{client_name}})
  2. 在渲染前验证数据
  3. 优雅处理缺失的数据
  4. 对模板进行版本控制

Installation

安装

bash
undefined
bash
undefined

Install required dependencies

Install required dependencies

pip install python-docx openpyxl python-pptx reportlab jinja2
undefined
pip install python-docx openpyxl python-pptx reportlab jinja2
undefined

Resources

资源