Deviopath › Python

Tiny Template Engine

Hard · Strings

Email and HTML templates fill placeholders from a context dict. Write render(template, context) that replaces placeholders of the form {{ path }}:

- spaces inside the braces are optional: {{name}} and {{ name }} both work

- a path is made of letters, digits, _ and dots. Dots walk into nested dicts: {{ user.name }} means context["user"]["name"]

- if any step of the path is missing, or the value at that step is not a dict, leave the placeholder exactly as written

- None renders as an empty string; other values are converted with str()

One neat way: re.sub with a replacement function, which receives each match and returns the text to put in its place.

Next: Format by Type with singledispatch