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 receives raw template source — such as "desk/"'s 904-character "newsroom/ — it immediately calls Template. 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 — 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, classifying it into one of four 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 byParser.parse.
Two details live inside the lexer rather than the parser. First, "{% verbatim %}" blocks are tracked right on "self.verbatim" inside Lexer so any "{{" or "{%" inside a verbatim region stays TokenType.TEXT until the matching "{% endverbatim %}" appears. Second, when Engine.debug is True, Template swaps Lexer for DebugLexer, which runs re 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 ("self), Parser ("self), and Parser ("del self) 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:
TokenType.TEXTappends aTextNode.TokenType.VARbuilds aFilterExpression, compiling aVariableand its"|"filter chain with compile-time argument count checks viaFilterExpression, and wraps it in a.args_check VariableNode. Note a Django6.1deprecation right insideParser.parse: double-dot lookups like"story..slug"now emitRemovedInDjango2028Warning.TokenType.BLOCKreads the first word (command = token). If.contents .split()[0] "command"is in"parse_until"— the list of closing tags expected by an enclosing block tag —Parser.parsepushes the closing token back onto"self.tokens"viaParserand returns the accumulated.prepend_token NodeListto its caller! Otherwise,Parser.parsepushes(command, token)onto"self(for.command_stack" "Unclosed tag on line ..."diagnostics), looks up"compile_func = self, and calls.tags[command]" "compile_func(self, token)"to compile the tag into aNode.
That recursive "parse_until" protocol is how every compound block tag works:
do_blockcalls"parser, then pops.parse(('endblock',))" "endblock"viaParser(verifying optional.next_token "endblock <name>"matches) and returns aBlockNode.do_forcalls"parser: if the terminating token is.parse(('empty', 'endfor'))" "empty", it consumes the token and calls"parsera second time to populate.parse(('endfor',))" ForNodealongside.nodelist_empty ForNode!.nodelist_loop do_extendscalls"parser.parse()"with no"parse_until"— consuming the entire remainder of the template intoExtendsNode, which is why.nodelist ExtendsNode(enforced by.must_be_first = True Parserchecking.extend_nodelist "nodelist) and why the top-level.contains_nontext" NodeListof"edition.html"contains only one node:ExtendsNode!
Watch Lexer.tokenize and Parser.parse compile "desk/"'s "newsroom/ live:
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 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.