---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# Cached loaders and automatic HTML escaping

How much time does the cached template loader save, and how does `VariableNode.render` decide whether to HTML-escape a value?

Every time a view calls `render(request, "newsroom/edition.html", context)`, Django has to find `"edition.html"` (and its parent `"base.html"`), produce compiled `Template` (`django/template/base.py:Template`) objects, resolve every variable in the tree, and escape untrusted strings before writing HTML to the response. Two small mechanisms govern the performance and safety of that hot path: the **cached template loader** (`django/template/loaders/cached.py:Loader`) and **`conditional_escape`** (`django/utils/html.py:conditional_escape`).

## How the cached loader works and caches misses

When `DEBUG=False` (and you have not overridden `"OPTIONS['loaders']"` manually), `Engine` (`django/template/engine.py:Engine`) automatically wraps the filesystem loader (`django/template/loaders/filesystem.py:Loader`) and the app-directories loader (`django/template/loaders/app_directories.py:Loader`) inside the **cached template loader** (`django/template/loaders/cached.py:Loader`).

Look at `Loader.get_template` (`django/template/loaders/cached.py:Loader.get_template`): it computes a cache key via `Loader.cache_key` (`django/template/loaders/cached.py:Loader.cache_key`) — combining `"template_name"` with a `hashlib.sha1` hash of any matching `"skip"` origins from recursive `"{% extends %}"` chains — looks up `"self.get_template_cache.get(key)"`, and on a hit returns the **exact same compiled `Template` (`django/template/base.py:Template`) instance** without touching the filesystem, `Lexer` (`django/template/base.py:Lexer`), or `Parser` (`django/template/base.py:Parser`) at all (`t1 is t2 == True`).

One subtle memory-safety detail sits right inside lines 58–61 of `django/template/loaders/cached.py`: negative caching for `TemplateDoesNotExist`. Apps with optional theme overrides frequently probe missing template names on every request, so the cached loader caches misses too — *but* raising a cached exception instance in Python attaches `__traceback__` frames holding live references to every local variable in the request stack, creating a massive memory leak! To prevent that leak:

- When `Engine.debug` is `False`, the cached loader caches the bare **`TemplateDoesNotExist` class** (not an instance!) and instantiates `"cached(template_name)"` fresh on each miss.
- When `Engine.debug` is `True`, it caches an unraised copy via `copy_exception` (`django/template/loaders/cached.py:Loader.get_template`) and raises a fresh copy on every lookup so debug `"tried"` lists survive without retaining tracebacks.

Measure the exact speedup of the cached loader rendering `"desk/"`'s `"newsroom/edition.html"` (which extends `"newsroom/base.html"` and renders four published stories) across `7` trials from `ch10-bench`:

```text recording=ch10-bench
1. Template get_template + render of edition.html (7 trials, us/render)
  loader_mode                 median_us   speedup
  uncached + debug=True          1261.3     1.00x
  uncached + debug=False         1237.0     1.02x
  cached   + debug=True           365.7     3.45x
  cached   + debug=False          353.2     3.57x
```

Look closely at those four rows. Turning `"debug=False"` without the cached loader barely moves the needle (`1,261.3 us -> 1,237.0 us`, `1.02x`), because disk reads plus `Lexer.tokenize` plus `Parser.parse` across two template files consume **`~884 us`** on every single request. Enabling the cached loader cuts that entire compilation phase to one dictionary lookup, dropping render time to **`353.2 us`** (**`3.57x` faster**)! Notice the operational consequence too: if you configure custom `"loaders"` in `"TEMPLATES"` for production without explicitly wrapping them in `"django.template.loaders.cached.Loader"`, you silently disable Django's default production template cache and pay `3.5x` latency on every page render!

## `VariableNode.render`, `render_value_in_context`, and `conditional_escape`

When a template reaches `{{ story.headline }}`, `VariableNode.render` (`django/template/base.py:VariableNode.render`) runs a strict two-stage pipeline:

1. **Resolution via `FilterExpression.resolve` and `Variable._resolve_lookup` (`django/template/base.py:Variable._resolve_lookup`):** Walks dotted segments trying dictionary key lookup first (`current[bit]`), then attribute lookup (`getattr(current, bit)`), then integer list indexing (`current[int(bit)]`). If the resolved object is callable, Django invokes it automatically with zero arguments *unless* `"do_not_call_in_templates = True"` (leaving the class or callable uncalled) or `"alters_data = True"` (blocking destructive methods like `Model.save` or `Model.delete` from ever executing inside a template!). Missing lookups silently evaluate to `"engine.string_if_invalid"` (`""` by default). Next, `FilterExpression.resolve` applies each `"|"` filter in order, passing `"autoescape=context.autoescape"` to filters marked `"needs_autoescape = True"` and preserving `SafeData` across filters marked `"is_safe = True"`.
2. **Formatting and escaping via `render_value_in_context` (`django/template/base.py:render_value_in_context`):** Converts datetimes to local time (`template_localtime`), localizes numbers and dates (`localize`), and then checks `"if context.autoescape:"` (which defaults to `True` on every `Context`). When autoescape is on, Django converts non-strings via `str(value)` and passes the result to **`conditional_escape`** (`django/utils/html.py:conditional_escape`):

```python
if isinstance(text, Promise):
    text = str(text)
if hasattr(text, "__html__"):
    return text.__html__()
else:
    return escape(text)
```

That `"hasattr(text, '__html__')"` check is the entire contract behind Django's XSS boundary (and also makes third-party HTML libraries like MarkupSafe interoperate natively!). Any plain Python `str` — such as a headline containing `<script>alert("x")</script>` — lacks `"__html__"`, so `escape()` replaces `&`, `<`, `>`, `"`, and `'` with HTML entities. Any `SafeString` returned by `mark_safe`, `format_html`, or `Widget.render` inherits from `SafeData` (which defines `__html__` returning `self`), so `conditional_escape` passes it through untouched without double-escaping it.

Watch the cached loader hit identity (`"t1 is t2"`) and `conditional_escape` handle raw XSS strings, `mark_safe`, and `"{% autoescape off %}"` live:

```text recording=ch10-presentation
3. Cached template loader and conditional_escape
  cached_loader: t1_is_t2=True cache_keys=['newsroom/edition.html']
  autoescape_plain = '&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;'
  autoescape_safe  = '<b>Breaking</b>'
  autoescape_off   = '<script>alert("x")</script>'
  conditional_escape(plain)='&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;' conditional_escape(safe)='<b>Breaking</b>'
```

Remember the one rule that breaks autoescaping silently: concatenating a `SafeString` with a plain Python `str` (`mark_safe("<b>") + user_input`) demotes the result back to plain `str` (causing double-escaping of `"<b>"`!), whereas wrapping user input inside `mark_safe(f"<b>{user_input}</b>")` bypasses `conditional_escape` completely and opens an XSS hole! Always compose dynamic HTML with `format_html` (`django/utils/html.py:format_html`), which runs `conditional_escape` on every argument before calling `mark_safe`.

That completes the outbound HTML side of presentation. Now we flip directions — following how Django builds forms, binds incoming `"POST"` data to widgets, and cleans untrusted user input — starting in [Form metaclasses, bound data, and widgets](form-binding.md).
