Pydantic Handlebars

0.1.0 · active · verified Thu Apr 16

pydantic-handlebars is an early-stage Python library, currently at version 0.1.0, that integrates the Handlebars templating engine with Pydantic for composing LLM prompts. It aims to provide structured, validated data from Pydantic models to Handlebars templates, primarily serving as an underlying component for projects like `pydantic-ai`. Due to its nascent stage, the release cadence is irregular, and the API is subject to change.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Pydantic model for structured data, create a Handlebars template string, and then render the template by passing the Pydantic model's data (converted to a dictionary) to the `HandlebarsTemplate`. It highlights how Pydantic ensures data validity before rendering and touches on potential Handlebars rendering issues for missing data.

from pydantic import BaseModel
from pydantic_handlebars import HandlebarsTemplate

class UserProfile(BaseModel):
    name: str
    title: str
    company: str

# Define your Handlebars template
template_string = """
Hello, my name is {{name}}.
I am a {{title}} at {{company}}.
"""

# Create a Pydantic model instance with data
user_data = UserProfile(name="Alice", title="Software Engineer", company="Acme Corp")

# Instantiate the HandlebarsTemplate with the template string
template = HandlebarsTemplate(template_string)

# Render the template using the Pydantic model's data
rendered_output = template.render(user_data.model_dump())
print(rendered_output)

# Example with missing data (will cause Pydantic validation error if not handled)
try:
    invalid_data = UserProfile(name="Bob", title="Manager") # Missing 'company'
except Exception as e:
    print(f"Caught expected error: {e.__class__.__name__}")

# Example of direct Handlebars rendering issues (e.g., missing variable in template context)
# This would typically be caught by Pydantic if the model was strict enough or template tried to access non-existent field.
loose_template_string = "Hello, {{missing_field}}!"
loose_template = HandlebarsTemplate(loose_template_string)
# This specific `render` call doesn't raise if 'missing_field' is just not found, but it highlights template data needs.
rendered_loose = loose_template.render({"name": "Charlie"})
print(f"Rendered with missing data (Handlebars default behavior): {rendered_loose}")

view raw JSON →