Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a template tag #1056

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/py/reactpy/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,27 @@ all = ["reactpy[starlette,sanic,fastapi,flask,tornado,testing]"]
starlette = [
"starlette >=0.13.6",
"uvicorn[standard] >=0.19.0",
"jinja2-simple-tags",
]
sanic = [
"sanic >=21",
"sanic-cors",
"uvicorn[standard] >=0.19.0",
"jinja2-simple-tags",
]
fastapi = [
"fastapi >=0.63.0",
"uvicorn[standard] >=0.19.0",
"jinja2-simple-tags",
]
flask = [
"flask",
"markupsafe>=1.1.1,<2.1",
"flask-cors",
"flask-sock",
"jinja2-simple-tags",
]
tornado = [
tornado = [ # TODO: Torando does not use Jinja. We will need to write something custom for this.
"tornado",
]
testing = [
Expand Down
44 changes: 44 additions & 0 deletions src/py/reactpy/reactpy/templatetag.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from jinja2_simple_tags import StandaloneTag
from uuid import uuid4
import urllib.parse

REACTPY_WEBSOCKET_URL: str
REACTPY_WEB_MODULES_URL: str
REACTPY_RECONNECT_MAX: str
REACTPY_CLIENT_URL: str


class ComponentTag(StandaloneTag):
"""This allows enables a `component` tag to be used in any Jinja2 rendering context."""
safe_output = True
tags = {"component"}

def render(self, dotted_path: str, *args, **kwargs):
uuid = uuid4().hex
class_ = kwargs.pop("class", "")
kwargs.pop("key", "") # `key` is effectively useless for the root node

# Generate the websocket URL
# TODO: This will require rewriting the websocket URL to `reactpy-ws/<uuid>?<kwargs>`
component_ws_url = f"{REACTPY_WEBSOCKET_URL}/{uuid}"
if kwargs.get("args") is not None:
raise ValueError("Cannot specify `args` as a keyword argument")
if args:
kwargs["args"] = args
if kwargs:
component_ws_url += f"?{urllib.parse.urlencode(kwargs)}"

return (
f'<div id="{ uuid }" class="{ class_ }"></div>'
'<script type="module" crossorigin="anonymous">'
f'import {{ mountViewToElement }} from "{REACTPY_CLIENT_URL}";'
f'const mountElement = document.getElementById("{ uuid }");'
"mountViewToElement("
" mountElement,"
f' "{ component_ws_url }",'
f' "{ REACTPY_WEB_MODULES_URL }",'
f' "{ REACTPY_RECONNECT_MAX }",'
f' "{ dotted_path }",'
");"
"</script>"
)