Closed jimbaker closed 11 months ago
In general, we don't want this in the PEP, because it relies on an implementation detail (Python code objects and their attributes); and it is nontrivial. But it's interesting that this is readily doable.
This could be a useful test for tag strings, at the very least, so I added that accordingly with https://github.com/pauleveritt/fdom/pull/20. I didn't do the last step of supporting gensym style symbols, but for testing that's not really necessary.
So far we have been looking at templates defined in Python code. There are many advantages in doing so, including use of Python modules, imports, etc.
However, Jinja and similar systems do allow ready definition of templates from arbitrary files/sources. Python also allows code to be evaluated from arbitrarily sources. Is it possible to generate templates accordingly?
Here's a sketch of a possible solution. Let's start with this function:
Create a template dynamically:
Define a function to pass in context:
NOTE: the use of
x[0][0]()
etc in the linef'{x[0][0]()} meet {x[2][0]()}'
is meant to represent compiled Python code, wherex[0][0]()
is an interpolation. So this is the equivalent of what is currently done in HTML compilation code.And this will go boom:
The problem here is that it's not possible as-is to use nested scopes with eval'ed code (https://docs.python.org/3/library/functions.html#eval). This is true even if we change
g
:Same error results:
But what if changed what we evaluated by knowing the variables
alice
andbob
are required?So let's try this code:
which works as expected.