Closed volfpeter closed 9 months ago
@volfpeter Great work. Small suggestion: Instead of using class names like Jinja that may cause confusion, can we call it something like HxTempl to differentiate? It won't matter much to the code, but makes the discussions easier. Also can you please give a quick example of how to set response cookies with this new update?
Small suggestion: Instead of using class names like Jinja that may cause confusion, can we call it something like HxTempl to differentiate?
The short answer is no. This lib is not a Jinja-specific one, so calling the Jinja-related classes anything else would be confusing. This would also be a breaking change, which I'd avoid as long as possible. If you prefer different names, you can alias these names in your imports.
Also can you please give a quick example of how to set response cookies with this new update?
I don't recommend doing it, but here is pattern:
def get_cookie_updates() -> dict:
# FastAPI dependency that returns an object that describes the changes you'd like to make to the response cookies
...
class JinjaWithCookieUpdate(Jinja):
def _make_response(
self,
template_name: str,
*,
jinja_context: dict[str, Any],
request: Request,
) -> HTMLResponse:
result = super._make_response(template_name, jinja_context=jinja_context, request: Request)
if "cookie_updates" in jinja_context:
# TODO: make the cookie changes on result
...
return result
jinja = JinjaWithCookieUpdate(
templates=Jinja2Templates("templates"),
make_context=JinjaContext.unpack_result_with_route_context
)
@app.post("/something")
def something(cookie_updates: dict = Depends(get_cookie_update)):
return None
Changes:
Jinja
now supports non-dict route return values by default. The conversion from such values to valid Jinja contexts (dict
) is done byJinjaContextFactory
methods with default implementations inJinjaContext
.Jinja.make_context
property.Jinja
instance's context factory on a per-route basis using themake_context
argument of the decorator.Jinja
got a new hook method_make_response()
for response customization.