Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM Tools
Machine Learning
Machine Learning & AI
Machine Learning Tools
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Helpers
Python Tips
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Dynamic Report Generation with Jinja Templates

Table of Contents

Dynamic Report Generation with Jinja Templates

F-strings are convenient for simple string interpolation, but they are tightly coupled with the surrounding Python code. They are typically used for a single, specific task.

metrics = {
    'accuracy': 0.95,
    'precision': 0.88,
    'recall': 0.92,
    'f1_score': 0.89,
    'auc_roc': 0.93,
    'specificity': 0.87
}

metrics_str = ""
for metric, value in metrics.items():
    if value > 0.9:
        metrics_str += f"{metric}: {value:.3f} (Excellent)\n"
    else:
        metrics_str += f"{metric}: {value:.3f} (Needs Improvement)\n"

print(metrics_str)
accuracy: 0.950 (Excellent)
precision: 0.880 (Needs Improvement)
recall: 0.920 (Excellent)
f1_score: 0.890 (Needs Improvement)
auc_roc: 0.930 (Excellent)
specificity: 0.870 (Needs Improvement)

Jinja’s templating engine is more versatile and powerful. It allows you to define templates with placeholders for dynamic data and supports conditionals, loops, and reuse across multiple contexts.

Use Jinja to perform complex templating tasks or generate dynamic reports.

# Jinja template version
from jinja2 import Template
template = Template("""
{% for metric, value in metrics.items() %}
    {% if value > 0.9 %}
    {{ metric }}: {{ value | round(3) }} (Excellent)
    {% else %}
    {{ metric }}: {{ value | round(3) }} (Needs Improvement)
    {% endif %}
{% endfor %}
""")

result = template.render(metrics=metrics)
print(result)
    accuracy: 0.95 (Excellent)



    precision: 0.88 (Needs Improvement)



    recall: 0.92 (Excellent)



    f1_score: 0.89 (Needs Improvement)



    auc_roc: 0.93 (Excellent)



    specificity: 0.87 (Needs Improvement)

Link to Jinja

Leave a Comment

Your email address will not be published. Required fields are marked *

0
    0
    Your Cart
    Your cart is empty
    Scroll to Top

    Work with Khuyen Tran

    Work with Khuyen Tran