Django 6.1.3

10.1 Templates and forms

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__ receives raw template source — such as "desk/"'s 904-character "newsroom/edition.html" — it immediately calls Template.compile_nodelist. Compilation happens in two fast, purely synchronous passes: a Lexer chops the text into a flat list of Token objects, and a recursive-descent Parser consumes those tokens into a tree of NodeList containers holding compiled Node subclasses.

Tokenizing in one regex pass

Open 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, classifying it into one of four TokenType values:

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, 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__:

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 loops while "self.tokens" is non-empty, dispatching on Token.token_type:

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

Watch Lexer.tokenize and Parser.parse compile "desk/"'s "newsroom/edition.html" live:

Recorded on Django 6.1.3 ch10-presentation script
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 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.