Skip to content
Parsing to AST
step 1/5

Reading — step 1 of 5

Read

~1 min readLexing & Parsing

Parsing to AST

After tokenization, build an AST representing the template structure.

Node types:

  • Text: literal text.
  • Var: variable reference + optional filters.
  • If: condition + then-block + optional else-block.
  • For: var + iterable + block.
  • Block: list of nodes (root, then-arm, else-arm, for-body).
  • Include: reference to another template.
  • Block (definition for inheritance).
python

Parser:

python

parse_if consumes the {% if cond %} token, then calls parse_block(tokens, until=['else','endif']). If next tag is else, it consumes and parses the else-block.

Errors:

  • Unclosed {% if %} without {% endif %} → SyntaxError.
  • {% endif %} without matching {% if %} → SyntaxError.
  • Unknown tag → SyntaxError.

Inside expressions (in {{ ... }}): mini-parser for the language. Could be:

  • Just identifier (Jinja2 default).
  • Full expressions: user.name | default("guest").
  • Method calls (some engines).
  • Function calls.

Most template engines have a restricted expression sub-language. Avoids "templates are full programs" risk.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…