volfpeter / fasthx

FastAPI server-side rendering with built-in HTMX support.
https://volfpeter.github.io/fasthx/
MIT License
458 stars 9 forks source link

Non-dict return value support for jinja #11

Closed volfpeter closed 9 months ago

volfpeter commented 9 months ago

Changes:

shawnsw commented 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?

volfpeter commented 9 months ago

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