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

# Lexing, parsing, and the NodeList tree

How do Django's template lexer and parser turn source text into a compiled tree of template nodes, and how do block tags consume tokens until their closing tag?

When `Template.__init__` (`django/template/base.py:Template.__init__`) receives raw template source — such as `"desk/"`'s 904-character `"newsroom/edition.html"` — it immediately calls `Template.compile_nodelist` (`django/template/base.py:Template.compile_nodelist`). Compilation happens in two fast, purely synchronous passes: a **`Lexer`** (`django/template/base.py:Lexer`) chops the text into a flat list of `Token` (`django/template/base.py:Token`) objects, and a recursive-descent **`Parser`** (`django/template/base.py:Parser`) consumes those tokens into a tree of **`NodeList`** (`django/template/base.py:NodeList`) containers holding compiled `Node` (`django/template/base.py:Node`) subclasses.

## Tokenizing in one regex pass

Open `Lexer.tokenize` (`django/template/base.py:Lexer.tokenize`) and notice how deliberately simple Django's scanner is. One precompiled regex — `tag_re = re.compile(r"({%.*?%}|{{.*?}}|{#.*?#})")` — splits the entire template string in a single pass. Because Python's `re.Pattern.split` with one capturing group alternates non-matching literal chunks and matching tag chunks, `Lexer.tokenize` simply flips an `"in_tag"` boolean on every element and hands each non-empty slice to `Lexer.create_token` (`django/template/base.py:Lexer.create_token`), classifying it into one of four `TokenType` (`django/template/base.py:TokenType`) values:

- **`TokenType.TEXT` (`0`):** Literal HTML text passed straight through verbatim.
- **`TokenType.VAR` (`1`):** Expressions inside `"{{" ... "}}"` with delimiters stripped (`"edition.title"`, `"story.corrections.all|length|pluralize"`).
- **`TokenType.BLOCK` (`2`):** Control tags inside `"{%" ... "%}"` (`"extends \"newsroom/base.html\""`, `"block content"`, `"for story in stories"`).
- **`TokenType.COMMENT` (`3`):** Single-line `"{# ... #}"` comments discarded immediately by `Parser.parse` (`django/template/base.py:Parser.parse`).

Two details live inside the lexer rather than the parser. First, `"{% verbatim %}"` blocks are tracked right on `"self.verbatim"` inside `Lexer.create_token` so any `"{{"` or `"{%"` inside a verbatim region stays `TokenType.TEXT` until the matching `"{% endverbatim %}"` appears. Second, when `Engine.debug` is `True`, `Template.compile_nodelist` swaps `Lexer` for `DebugLexer` (`django/template/base.py:DebugLexer`), which runs `re.Pattern.finditer` over `tag_re` instead of `split` so every `Token` records its exact `(start, end)` character offsets for Django's debug error page.

## Recursive-descent parsing and block tags

Look at the very first line of `Parser.__init__` (`django/template/base.py:Parser.__init__`):

```python
self.tokens = list(reversed(tokens))
```

Reversing the token stream once lets `Parser.next_token` (`"self.tokens.pop()"`), `Parser.prepend_token` (`"self.tokens.append(token)"`), and `Parser.delete_first_token` (`"del self.tokens[-1]"`) all run in **`O(1)`** time at the tail of the list instead of shifting a list from index `0` on every token!

`Parser.parse` (`django/template/base.py:Parser.parse`) loops while `"self.tokens"` is non-empty, dispatching on `Token.token_type` (`django/template/base.py:Token`):

- `TokenType.TEXT` appends a `TextNode` (`django/template/base.py:TextNode`).
- `TokenType.VAR` builds a `FilterExpression` (`django/template/base.py:FilterExpression`), compiling a `Variable` and its `"|"` filter chain with compile-time argument count checks via `FilterExpression.args_check`, and wraps it in a `VariableNode` (`django/template/base.py:VariableNode`). Note a Django `6.1` deprecation right inside `Parser.parse`: double-dot lookups like `"story..slug"` now emit `RemovedInDjango2028Warning`.
- `TokenType.BLOCK` reads the first word (`command = token.contents.split()[0]`). If `"command"` is in `"parse_until"` — the list of closing tags expected by an enclosing block tag — `Parser.parse` **pushes the closing token back onto `"self.tokens"` via `Parser.prepend_token` and returns the accumulated `NodeList` to its caller**! Otherwise, `Parser.parse` pushes `(command, token)` onto `"self.command_stack"` (for `"Unclosed tag on line ..."` diagnostics), looks up `"compile_func = self.tags[command]"`, and calls `"compile_func(self, token)"` to compile the tag into a `Node` (`django/template/base.py:Node`).

That recursive `"parse_until"` protocol is how every compound block tag works:

- `do_block` (`django/template/loader_tags.py:do_block`) calls `"parser.parse(('endblock',))"`, then pops `"endblock"` via `Parser.next_token` (verifying optional `"endblock <name>"` matches) and returns a `BlockNode` (`django/template/loader_tags.py:BlockNode`).
- `do_for` (`django/template/defaulttags.py:do_for`) calls `"parser.parse(('empty', 'endfor'))"`: if the terminating token is `"empty"`, it consumes the token and calls `"parser.parse(('endfor',))"` a *second* time to populate `ForNode.nodelist_empty` (`django/template/defaulttags.py:ForNode`) alongside `ForNode.nodelist_loop`!
- `do_extends` (`django/template/loader_tags.py:do_extends`) calls `"parser.parse()"` with **no `"parse_until"`** — consuming the *entire remainder* of the template into `ExtendsNode.nodelist` (`django/template/loader_tags.py:ExtendsNode`), which is why `ExtendsNode.must_be_first = True` (enforced by `Parser.extend_nodelist` checking `"nodelist.contains_nontext"`) and why the top-level `NodeList` of `"edition.html"` contains only **one** node: `ExtendsNode`!

Watch `Lexer.tokenize` (`django/template/base.py:Lexer.tokenize`) and `Parser.parse` compile `"desk/"`'s `"newsroom/edition.html"` live:

```text recording=ch10-presentation
1. Lexer.tokenize and Parser.parse over desk edition.html
  edition.html: chars=904 tokens=48 counts=TEXT:22,VAR:9,BLOCK:17
  first_8_tokens:
    L01 BLOCK 'extends "newsroom/base.html"'
    L01 TEXT  '\\n'
    L02 BLOCK 'block title'
    L02 BLOCK 'if edition'
    L02 VAR   'edition.title'
    L02 TEXT  ' — '
    L02 VAR   'edition.slug'
    L02 BLOCK 'else'
  top_nodelist = ['ExtendsNode']
  extends_parent='"newsroom/base.html"' blocks=['title', 'content'] if_nodes=3 for_nodes=1 for_loop_children=11 for_empty_children=1
```

Notice how Django `6.0+` also builds **template partials** via `PartialTemplate` (`django/template/base.py:PartialTemplate`) on top of this exact `NodeList` mechanism — capturing a named sub-`NodeList` inside `"parser.extra_data"` during parsing so views can render a fragment directly without splitting it into a separate file.

Compilation produces an immutable tree of `Node` objects. Next we watch that tree execute against live request data — how `Context` stacks scopes, how `ExtendsNode` merges child and parent blocks through `BlockContext`, and why mutating `self` inside a `Node` leaks data across users — in [Context, RenderContext, and inheritance](context-and-rendering.md).
