Reading — step 1 of 5
Read
~2 min readInheritance & Production
Production Template Engines
Operating templates in production:
Compilation + caching:
- Templates parsed → AST → compiled to functions (Python bytecode, Go funcs).
- Cache compiled forms; recompile on file change in dev.
- Production: compile once at startup; freeze.
Sandboxing:
- User-supplied templates can be RCE if engine evaluates Python expressions.
- Jinja2 SandboxedEnvironment: restricts attribute access.
- Whitelist of safe methods.
- Prefer: don't accept user-supplied templates.
Performance:
- AST traversal per render: 100k req/sec sustainable.
- Compiled bytecode: 1M req/sec.
- Hot path: avoid filter chains; pre-compute in code.
Error handling:
- TemplateNotFound: missing file.
- TemplateSyntaxError: parse error.
- UndefinedError: missing var (in strict mode).
- TypeError: filter applied to wrong type.
Stack traces: include template name + line. Hard if templates compiled to Python bytecode (line numbers may not align).
Static analysis:
- Detect undefined variables before render.
- Detect XSS risks (raw output of user data).
- Tools: jinjalint, djLint.
Internationalization (i18n):
{% trans %}{{ greeting }}, world{% endtrans %}→ translation table lookup.- Pluralization:
{% pluralize count %}1 item{% pluralize %}{{ count }} items{% endpluralize %}.
HTML safety:
- Auto-escape HTML mode (default).
- Per-context escapers (HTML attribute, URL, JS string, CSS).
- Audit
| safeand| rawusages.
Modern alternatives:
- JSX/TSX: React. Templates ARE code.
- Component-based: Vue, Svelte, Solid. Compile templates to optimized JS.
- Server components: Next.js, Remix. Render on server, hydrate on client.
- HTMX: server returns HTML fragments; minimal client-side JS.
Template engines used today:
- Jinja2: Python web (Flask, Django optional).
- ERB: Rails.
- EJS: Express.js.
- Handlebars: client-side JS.
- Mustache: cross-language, simple.
- Liquid: Shopify, Jekyll.
- html/template: Go std lib.
When you should use a template engine:
- Server-rendered HTML.
- Email composition.
- Code/config generation (Helm, Ansible).
When you should NOT:
- SPA / SSR with React/Vue/Svelte.
- Highly interactive UI.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…