Closed graingert closed 4 months ago
I'd like to see a cmgr/closing block so I can do:
<html>
<head></head>
<body>
{% closing model.objects.all() as agen %}
{% for m in agen %}
{{ m }}
{% break %}
{% endfor %}
{% endclosing %}
</body>
</html>
but with all the changes in https://github.com/pallets/jinja/pull/1960 it's possible pass in an aclosing
function to context:
import sys
import trio
import contextlib
from jinja2 import Template, select_autoescape
class MyModel:
class objects:
@staticmethod
async def all():
while True:
yield "hello"
template = """
<html>
<head></head>
<body>
{% for m in aclosing(model.objects.all()) %}
{{ m }}
{% break %}
{% endfor %}
</body>
</html>
"""
async def amain():
async with contextlib.AsyncExitStack() as stack:
def aclosing(agen):
stack.push_async_callback(agen.aclose)
return agen
return await Template(
source=template, enable_async=True, extensions=["jinja2.ext.loopcontrols"]
).render_async(model=MyModel, aclosing=aclosing)
def main():
trio.run(amain)
if __name__ == "__main__":
sys.exit(main())
given:
this results in:
but there's no way to wrap generators with
async with aclosing(...):
in jinja2Environment: