Template Variable Interpolation Engine ({{var}})
Micro-rendering engines replace double-curly-bracket placeholders (`{{var}}`) with runtime context values. Robust implementations resolve nested dotted paths (`{{user.profile.name}}`), strip internal whitespace, and gracefully supply default fallbacks when keys are missing without crashing on `KeyError` 🧬📄⚡.
import re
PATTERN = re.compile(r"\{\{\s*([a-zA-Z0-9_.]+)\s*\}\}")
def get_nested(data, path, fallback=""):
curr = data
for key in path.split("."):
if isinstance(curr, dict) and key in curr: curr = curr[key]
else: return fallback
return str(curr)
def render(tmpl, ctx):
return PATTERN.sub(lambda m: get_nested(ctx, m.group(1)), tmpl)
print(render("Welcome {{ user.name }}!", {"user": {"name": "Alice"}}))
# 10. Template Variable Interpolation Engine ({{var}}) Frameworks like Jinja, Liquid, and Mustache power HTML generation, email dispatchers, and code generation pipelines. At their core is a clean text interpolation engine that replaces double-brace tokens with variables 🛑. ```python # The Interpolation Model: # Template: "Deploying commit {{ git.sha }} to {{ env }} on host {{ server.host }}." # Context: {"git": {"sha": "c0ffee"}, "env": "prod", "server": {"host": "node-1"}} # Output: "Deploying commit c0ffee to prod on host node-1." ``` ### Critical Production Invariants 1. **Permissive Whitespace**: Users write `{{name}}`, `{{ name }}`, or `{{ name }}`. The regex `\{\{\s*([a-zA-Z0-9_.]+)\s*\}\}` normalizes spacing seamlessly. 2. **Deep Dotted Traversal**: Splitting on `.` enables nested dictionary inspection (`git.author.email`) without needing messy nested string lookups in client code. 3. **Graceful Degradation**: Never crash the entire page or mail delivery because an optional profile property is missing. Substitute an empty string or a configurable default fallback 🧬📄⚡. --- ### Interactive Pop-Quiz 🧠 #### Why should a production template interpolation engine use safe dotted navigation rather than naive dict[key] lookups? - [ ] Dotted traversal prevents KeyError and TypeError exceptions if intermediate keys are absent, returning clean defaults instead of 500 errors 🛡️ - [ ] Because Python forbids square bracket indexing in string formatters - [ ] Dotted paths run in hardware-accelerated CPU registers - [ ] Square brackets cannot be parsed by regular expressions --- ### Practical Challenge 🎯 Implement `render_template(template: str, context: dict, default: str = '') -> str` matching `{{ path }}`. Resolve nested dotted paths like `'user.name'`. If any intermediate key is missing, return `default`. Test with `'Hello {{ user.name }}, your balance is ${{ account.balance }} (tier: {{ missing.tier }}).'`, with context `{'user': {'name': 'Alice'}, 'account': {'balance': 1450}}` and `default='N/A'`, assert results, and print output. <details> <summary>Solution</summary> ```python import re TEMPLATE_VAR_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_.]+)\s*\}\}") def resolve_dotted_path(ctx: dict, path: str, default: str = ""): parts = path.split(".") curr = ctx for part in parts: if isinstance(curr, dict) and part in curr: curr = curr[part] else: return default return str(curr) def render_template(template: str, context: dict, default: str = "") -> str: def replacer(match): path = match.group(1) return resolve_dotted_path(context, path, default) return TEMPLATE_VAR_RE.sub(replacer, template) tmpl = "Hello {{ user.name }}, your balance is ${{ account.balance }} (tier: {{ missing.tier }})." ctx = { "user": {"name": "Alice"}, "account": {"balance": 1450} } out = render_template(tmpl, ctx, default="N/A") assert "Hello Alice" in out assert "$1450" in out assert "(tier: N/A)" in out print(f"Template rendered successfully: '{out}'") ``` </details>