Skip to content

Commit

Permalink
Merge pull request #32 from volfpeter/jinja/globally-disable-data-res…
Browse files Browse the repository at this point in the history
…ponse

Added the Jinja.no_data property
  • Loading branch information
volfpeter authored Sep 9, 2024
2 parents 256b12f + d7a0bc6 commit d4d293f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
10 changes: 9 additions & 1 deletion fasthx/jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,14 @@ class Jinja:
a Jinja rendering context. The default value is `JinjaContext.unpack_result`.
"""

no_data: bool = field(default=False, kw_only=True)
"""
If set, `hx()` routes will only accept HTMX requests.
Note that if this property is `True`, then the `hx()` decorator's `no_data` argument
will have no effect.
"""

def hx(
self,
template: ComponentSelector[str],
Expand Down Expand Up @@ -304,7 +312,7 @@ def hx(
render_error=None
if error_template is None
else self._make_render_function(error_template, make_context=make_context, prefix=prefix),
no_data=no_data,
no_data=self.no_data or no_data,
)

def page(
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "fasthx"
version = "2.0.0-rc2"
version = "2.0.0-rc3"
description = "FastAPI data APIs with HTMX support."
authors = ["Peter Volf <[email protected]>"]
readme = "README.md"
Expand Down
12 changes: 10 additions & 2 deletions tests/test_jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def jinja_app() -> FastAPI:
app = FastAPI()

jinja = Jinja(Jinja2Templates("tests/templates"))
no_data_jinja = Jinja(Jinja2Templates("tests/templates"), no_data=True)

@app.get("/")
@jinja.page("user-list.jinja")
Expand Down Expand Up @@ -113,6 +114,11 @@ def error(response: Response) -> None:
def error_page(response: Response) -> None:
raise RenderedError({"a": 1, "b": 2}, response=response)

@app.get("/global-no-data")
@no_data_jinja.hx("user-list.jinja", no_data=False)
def global_no_data() -> list[User]:
return []

return app


Expand Down Expand Up @@ -186,10 +192,12 @@ def jinja_client(jinja_app: FastAPI) -> TestClient:
("/htmx-only", {"HX-Request": "true"}, 200, user_list_html, {}),
("/htmx-only", None, 400, "", {}),
("/htmx-only", {"HX-Request": "false"}, 400, "", {}),
# hx error rendering
# hx() error rendering
("/error", {"HX-Request": "true"}, 456, "Hello World!", {}),
# page error rendering
# page() error rendering
("/error-page", None, 456, "Hello World!", {}),
# Globally disabled data responses
("/global-no-data", None, 400, "", {}),
),
)
def test_jinja(
Expand Down

0 comments on commit d4d293f

Please sign in to comment.