|
8 | 8 | import time
|
9 | 9 | from typing import Any, Optional, Sequence, Type, Union
|
10 | 10 |
|
11 |
| -import orjson |
12 | 11 | from starlette.requests import Request
|
13 | 12 | from starlette.templating import Jinja2Templates, _TemplateResponse
|
14 | 13 |
|
@@ -42,48 +41,53 @@ def _newfn(*args: Any, **kwargs: Any):
|
42 | 41 |
|
43 | 42 | def create_html_response(
|
44 | 43 | request: Request,
|
45 |
| - data: str, |
| 44 | + data: Any, |
46 | 45 | templates: Jinja2Templates,
|
47 | 46 | template_name: str,
|
| 47 | + title: Optional[str] = None, |
48 | 48 | router_prefix: Optional[str] = None,
|
| 49 | + **kwargs: Any, |
49 | 50 | ) -> _TemplateResponse:
|
50 | 51 | """Create Template response."""
|
51 | 52 | urlpath = request.url.path
|
52 | 53 | if root_path := request.app.root_path:
|
53 | 54 | urlpath = re.sub(r"^" + root_path, "", urlpath)
|
54 | 55 |
|
| 56 | + if router_prefix: |
| 57 | + urlpath = re.sub(r"^" + router_prefix, "", urlpath) |
| 58 | + |
55 | 59 | crumbs = []
|
56 | 60 | baseurl = str(request.base_url).rstrip("/")
|
57 | 61 |
|
| 62 | + if router_prefix: |
| 63 | + baseurl += router_prefix |
| 64 | + |
58 | 65 | crumbpath = str(baseurl)
|
| 66 | + if urlpath == "/": |
| 67 | + urlpath = "" |
| 68 | + |
59 | 69 | for crumb in urlpath.split("/"):
|
60 | 70 | crumbpath = crumbpath.rstrip("/")
|
61 |
| - |
62 | 71 | part = crumb
|
63 | 72 | if part is None or part == "":
|
64 | 73 | part = "Home"
|
65 |
| - |
66 | 74 | crumbpath += f"/{crumb}"
|
67 | 75 | crumbs.append({"url": crumbpath.rstrip("/"), "part": part.capitalize()})
|
68 | 76 |
|
69 |
| - if router_prefix: |
70 |
| - baseurl += router_prefix |
71 |
| - |
72 | 77 | return templates.TemplateResponse(
|
73 |
| - f"{template_name}.html", |
74 |
| - { |
75 |
| - "request": request, |
76 |
| - "response": orjson.loads(data), |
| 78 | + request, |
| 79 | + name=f"{template_name}.html", |
| 80 | + context={ |
| 81 | + "response": data, |
77 | 82 | "template": {
|
78 | 83 | "api_root": baseurl,
|
79 | 84 | "params": request.query_params,
|
80 |
| - "title": "", |
| 85 | + "title": title or template_name, |
81 | 86 | },
|
82 | 87 | "crumbs": crumbs,
|
83 |
| - "url": str(request.url), |
84 |
| - "baseurl": baseurl, |
85 |
| - "urlpath": str(request.url.path), |
86 |
| - "urlparams": str(request.url.query), |
| 88 | + "url": baseurl + urlpath, |
| 89 | + "params": str(request.url.query), |
| 90 | + **kwargs, |
87 | 91 | },
|
88 | 92 | )
|
89 | 93 |
|
|
0 commit comments