Template Engine Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Template Engine runs in O(n) time and O(n) space, in Python as in every other language.
- ✓`string.Formatter().parse()` is the tokeniser nobody remembers: it yields `(literal_text, field_name, format_spec, conversion)` tuples straight out of a format string.
- ✓Bind loop variables into default arguments when you build the step closures. `lambda ctx, out: out.append(literal)` captures the name, not the value, so every literal step emits whatever `literal` held on the final iteration; `lambda ctx, out, lit=literal: ...` freezes it at compile time.
- ✓The Python trap: Reach for `str.format` as the hole syntax and you have shipped an information disclosure hole.
- ✓`html.escape` is five sequential `str.replace` calls, so an escaped value can cost five intermediate string objects before anything reaches your buffer; skipping the call when the value contains none of `&<>"'` pays for itself on numeric columns.
What Template Engine actually is
Template Engine in Python: what you actually reach for
Python implementation
import html, re
from functools import lru_cache
TOKEN = re.compile(r"\{\{\s*(?P<raw>&\s*)?(?P<name>[A-Za-z_]\w*)\s*\}\}")
class Safe(str):
"""Raw opt-out. Follows the __html__ protocol markupsafe and Jinja2 honour."""
def __html__(self) -> str:
return str(self)
def _emit(value) -> str:
hook = getattr(value, "__html__", None) # trusted values declare themselves
return hook() if hook else html.escape(str(value), quote=True)
@lru_cache(maxsize=512) # cache keyed on the source text
def compile_template(source: str) -> tuple:
steps, pos = [], 0
for m in TOKEN.finditer(source):
if m.start() > pos:
# lit=... binds now; a bare closure over the loop var would emit
# the final chunk from every literal step.
steps.append(lambda ctx, out, lit=source[pos:m.start()]: out.append(lit))
key, raw = m.group("name"), bool(m.group("raw"))
if raw:
steps.append(lambda ctx, out, k=key: out.append(str(ctx[k])))
else:
steps.append(lambda ctx, out, k=key: out.append(_emit(ctx[k])))
pos = m.end()
if pos < len(source):
steps.append(lambda ctx, out, lit=source[pos:]: out.append(lit))
return tuple(steps)
def render(source: str, ctx: dict) -> str:
out = []
for step in compile_template(source): # compiled once, replayed per render
step(ctx, out)
return "".join(out) # one join, never += in a loop
ROW = "<td>{{platform}}</td><td>{{ status }}</td><td>{{& badge }}</td>"
print(render(ROW, {"platform": "4B", "status": 'delayed <20" min>',
"badge": Safe("<em>live</em>")}))
print(compile_template.cache_info())Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Template Engine?
`string.Formatter().parse()` is the tokeniser nobody remembers: it yields `(literal_text, field_name, format_spec, conversion)` tuples straight out of a format string. `html.escape(s, quote=True)` is the encoder, `functools.lru_cache` is the plan cache, and the builtin `compile()` is how the ecosystem's real engine works, since Jinja2 generates Python source per template and compiles it to a code object. MarkupSafe, Jinja2's dependency, defines the `__html__` protocol that `markupsafe.escape` honours; the stdlib `html.escape` knows nothing about it, so the trusted-value wrapper is yours to write.
What is the most common Python mistake when implementing Template Engine?
Reach for `str.format` as the hole syntax and you have shipped an information disclosure hole. `Formatter.get_field` walks the dotted path written in the format string using `getattr`, so a template author writes `{row.__init__.__globals__[SECRET]}` and CPython obligingly traverses function to module globals and prints your key. This is exactly why `string.Template` exists: it accepts only `$name` and never touches attributes. If the template text is not fully trusted, `str.format` is disqualified before escaping even enters the conversation, and no amount of output encoding repairs it.
How does Template Engine actually perform in Python?
`html.escape` is five sequential `str.replace` calls, so an escaped value can cost five intermediate string objects before anything reaches your buffer; skipping the call when the value contains none of `&<>"'` pays for itself on numeric columns. Accumulate into a list and join once, because CPython's in-place `+=` fast path only fires while the target string has a refcount of one. `lru_cache` hashes its key, and CPython memoises a string's hash on the object, so a module-level template constant costs a pointer-sized lookup while a string rebuilt per request re-hashes its full length every time. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.