Skip to main content

Overview

DocuGen AI uses Jinja2 as its template engine to generate README files. The template system is flexible, allowing you to customize the output format and structure of generated documentation.

Template Engine Architecture

The TemplateEngine class (docugen/templates/engine.py:11) manages template rendering:
class TemplateEngine:
    def __init__(self, template_dir: str | Path | None = None) -> None:
        base_dir = Path(template_dir) if template_dir else Path(__file__).resolve().parent
        self.environment = Environment(
            loader=FileSystemLoader(str(base_dir)),
            autoescape=False,
            trim_blocks=True,
            lstrip_blocks=True,
        )

Configuration Options

OptionValuePurpose
autoescapeFalseAllows raw Markdown output without HTML escaping
trim_blocksTrueRemoves newlines after template blocks
lstrip_blocksTrueStrips whitespace before blocks for cleaner output

Default Template Structure

The default template (default_readme.md.j2) receives three context variables:
# {{ project_name }}

> Generated by DocuGen AI.

{% if summary %}
## Analysis Summary

- Python files scanned: {{ summary["file_count"] }}
- Classes detected: {{ summary["class_count"] }}
- Top-level functions detected: {{ summary["function_count"] }}
- Methods detected: {{ summary["method_count"] }}
- Parsing errors: {{ summary["error_count"] }}
{% endif %}

## Technical Documentation

{{ ai_content }}

Template Context Variables

project_name
string
The name of the project being documented
ai_content
string
AI-generated technical documentation from Gemini API
summary
dict
default:"{}"
Project analysis metrics including:
  • file_count: Number of Python files scanned
  • class_count: Total classes found
  • function_count: Top-level functions
  • method_count: Methods within classes
  • error_count: Parsing errors encountered

Creating Custom Templates

Step 1: Create Template File

Create a new .j2 file in your templates directory:
custom_readme.md.j2
# πŸš€ {{ project_name }}

**AI-Powered Documentation**

---

## πŸ“Š Project Statistics

{% if summary %}
| Metric | Count |
|--------|-------|
| Files | {{ summary.file_count }} |
| Classes | {{ summary.class_count }} |
| Functions | {{ summary.function_count }} |
| Methods | {{ summary.method_count }} |
{% endif %}

## πŸ“– Documentation

{{ ai_content }}

---
*Generated on {{ timestamp }}*

Step 2: Use Custom Template

from docugen.templates.engine import TemplateEngine

engine = TemplateEngine(template_dir="/path/to/templates")
output = engine.render(
    "custom_readme.md.j2",
    {
        "project_name": "My Project",
        "ai_content": "Documentation content...",
        "summary": {
            "file_count": 15,
            "class_count": 8,
            "function_count": 23,
            "method_count": 42,
        },
        "timestamp": "2026-03-10"
    }
)

Advanced Customization

Adding Custom Filters

Extend the Jinja2 environment with custom filters:
from docugen.templates.engine import TemplateEngine

engine = TemplateEngine()
engine.environment.filters['uppercase'] = lambda x: x.upper()
Then in your template:
# {{ project_name | uppercase }}

Conditional Sections

Add logic-based content rendering:
{% if summary.error_count > 0 %}
## ⚠️ Parsing Warnings

This project encountered {{ summary.error_count }} parsing errors.
Review the code for syntax issues.
{% endif %}

{% if summary.class_count > 10 %}
## πŸ—οΈ Complex Architecture

This is a large project with {{ summary.class_count }} classes.
{% endif %}

Loops and Iteration

If you extend the context with additional data:
{% if files %}
## πŸ“ File Breakdown

{% for file in files %}
- **{{ file.path }}**: {{ file.line_count }} lines
{% endfor %}
{% endif %}

Template Best Practices

Keep Templates Simple

Templates should focus on structure and formatting. Leave complex logic in Python code.

Use Whitespace Control

Leverage trim_blocks and lstrip_blocks to keep generated Markdown clean.

Provide Fallbacks

Always use conditional checks ({% if summary %}) for optional data.

Test Thoroughly

Test templates with various data scenarios including missing fields and edge cases.

Rendering API

The render() method (docugen/templates/engine.py:21) handles template execution:
def render(self, template_name: str, context: dict[str, Any]) -> str:
    template = self.environment.get_template(template_name)
    rendered = template.render(**context).strip()
    return f"{rendered}\n"
The method automatically strips whitespace and ensures the output ends with a single newline.

Common Use Cases

Multi-Format Output

Create templates for different documentation formats:
  • readme.md.j2 - Standard README
  • api_docs.md.j2 - API reference format
  • changelog.md.j2 - Change log format
  • wiki.md.j2 - Wiki-style documentation

Internationalization

Create language-specific templates:
readme_es.md.j2
# {{ project_name }}

> Generado por DocuGen AI.

{% if summary %}
## Resumen del AnΓ‘lisis

- Archivos Python escaneados: {{ summary.file_count }}
- Clases detectadas: {{ summary.class_count }}
{% endif %}

Brand Customization

Add company branding and style:
# {{ project_name }}

![Company Logo](https://example.com/logo.png)

**Developed by Acme Corp**

{{ ai_content }}

---
Β© 2026 Acme Corp. All rights reserved.

Build docs developers (and LLMs) love