Writing a Jinja-inspired template library in Python

submited by
Style Pass
2021-05-23 19:00:07

In this post we'll build a minimal text templating library in Python inspired by Jinja. It will be able to display variables and iterate over arrays.

In this templating language, pytemplate, {% $function () %} ... {% end$function %} blocks are specially evaluated depending on the particular function being called. For example, the for-in ($iter_name, $array) function will duplicate its children for every element in $array. Within the body of the loop, the variable $iter_name will exist and be set to the current element in the array.

Function arguments are expressions (or nodes as we'll call them). They can be strings (surrounded by single quotes), identifiers found in a provided dictionary (or environment as we'll call it), or nested function calls (also called nodes).

The non-block syntax {{ ... }} are just called tags. The inside of a tag is a node and is evaluated the same way a function argument is.

Leave a Comment