How to Render a Jinja-like Template from a Dict in Python
Replace {{placeholders}} in a string using values from a Python dict with a simple regex-based template renderer.
Python code
14 linesimport re
def render_template(template, context):
pattern = re.compile(r"\{\{\s*(\w+)\s*\}\}")
def replace(match):
key = match.group(1)
return str(context.get(key, ""))
return pattern.sub(replace, template)
if __name__ == "__main__":
template = "Hello {{name}}, you have {{count}} new messages."
context = {"name": "Alice", "count": 5}
result = render_template(template, context)
print(result)
Output
Hello Alice, you have 5 new messages.
How it works
The regex pattern \{\{\s*(\w+)\s*\}\} matches {{ followed by optional spaces, a word (the key), optional spaces, and }}. The replace function looks up the captured key in the context dict and returns the string value, defaulting to an empty string when the key is missing. re.sub walks through the template, replacing every match with the result. This gives a lightweight, dependency-free way to render simple placeholders without pulling in Jinja2.
Common mistakes
- Forgetting to escape braces in the regex when building the pattern manually.
- Missing keys silently become empty strings instead of raising an error or showing a placeholder.
- Values that are not strings (e.g., int, float) cause a TypeError unless you call str() on them.
Variations
- Use a lambda instead of a named replace function: `re.sub(pattern, lambda m: str(context.get(m.group(1), '')), template)`
- Switch to Jinja2's `Template(template).render(context)` when you need filters, conditionals, or loops.
Real-world use cases
- Render dynamic prompt templates in LLM apps where user input is slotted into a fixed instruction string.
- Generate personalized email or notification bodies from a dict of user attributes.
- Build config file templates that substitute environment-specific values at deploy time.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.