Most pages on a site share some content
Many pages want to be customized based on data
So many sites use a templating system
Embed commands in an existing language like [EJS][ejs]
Create a mini-language with its own commands like [Jekyll][jekyll]
Put directives in specially-named attributes in the HTML
[% figure slug=“template-options” img=“design_options.svg” alt=“Three options for page templates” caption=“Three different ways to implement page templating.” %]
[%inc loop.ht %]
z-loop: repeat this
z-num: a constant number
z-var: fill in a variable
z-if: conditional
[%inc loop.out %]
[%inc example_call.py %]
data would come from a configuration file
or databaseChainMap, but we’ll write our own[%inc env.py mark=body %]
[%inc visitor.py %]
[%inc expander.py mark=construct %]
The environment
Handlers for our special node types
The result (strings we’ll concatenate at the end)
[%inc expander.py mark=open %]
If this is text, “display” it
If this is a special node, run a function
Otherwise, show the opening tag
Return value is “do we proceed”?
[%inc expander.py mark=close %]
Handlers come in open/close pairs
[%inc expander.py mark=handlers %]
hasHandler looks for attributes with special
names
getHandler gets the one we need
[%inc z_num.py %]
A module with open and close
functions
None of our handlers need state, so we don’t need objects
[%inc z_var.py %]
[%inc template.py %]
[%inc static_text.ht %] [%inc static_text.out %]
[%inc single_constant.ht %] [%inc single_constant.out %]
[%inc single_variable.ht %] [%inc single_variable.out %]
{"varName": "varValue"}[%inc z_if.py %]
The handler determines whether to show this tag and go deeper
What if the variable’s value changes between opening and closing?
[%inc conditional.ht %] [%inc conditional.out %]
{"yes": True, "no": False}Create a new stack frame holding the current value of the loop variable
Expand all of the node’s children with that stack frame in place
Pop the stack frame to get rid of the temporary variable
[%inc z_loop.py %]
[%inc loop.ht %] [%inc loop.out %]
The z-if issue might mean we need state after
all
Tackle that before going any further
And figure out how to do unit testing
[% figure slug=“template-concept-map” img=“concept_map.svg” alt=“Concept map for page templates” caption=“Concept map.” %]