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.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 14 views 0 copies

Python code

14 lines
Python 3.9+
import 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

stdout
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

  1. Use a lambda instead of a named replace function: `re.sub(pattern, lambda m: str(context.get(m.group(1), '')), template)`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.