Skip to content

Commit

Permalink
Close #26: treat tags.script like an HTML dependency inside of JSXTag
Browse files Browse the repository at this point in the history
  • Loading branch information
cpsievert committed Apr 7, 2022
1 parent a78b32a commit bde4d1b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
7 changes: 7 additions & 0 deletions htmltools/_jsx.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
HTML,
MetadataNode,
HTMLDependency,
head_content,
)
from ._versions import versions

Expand Down Expand Up @@ -123,6 +124,12 @@ def tagify(self) -> Tag:
# metadata nodes. This could be done in two separate passes, but it's more
# efficient to do it in one pass.
def tagify_tagifiable_and_get_metadata(x: Any) -> Any:
if isinstance(x, Tag) and x.name == "script":
# React.createElement("script") won't invoke it's contents in the same
# way ordinary HTML tags do, but we can circumvent that by 'hoisting' it
# as head_content.
metadata_nodes.append(head_content(x))
x = MetadataNode()
if isinstance(x, Tagifiable) and not isinstance(x, (Tag, JSXTag)):
x = x.tagify()
else:
Expand Down
20 changes: 17 additions & 3 deletions tests/test_jsx_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ def test_jsx_tags():
jsx("`childexpression`"),
Foo(),
[Foo(), Bar()],
tags.script("alert('hello')"),
TagList(Foo(), Bar()),
span(Foo(span()), Bar()),
int=1,
Expand All @@ -84,9 +85,19 @@ def test_jsx_tags():
string="string",
list=[1, 2, 3],
)
assert str(x) == textwrap.dedent(
assert HTMLDocument(x).render()["html"] == textwrap.dedent(
"""\
<script type="text/javascript" data-needs-render="">
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script type="application/html-dependencies">react[%s];react-dom[%s];headcontent_eb156e81fa07b6cf22e580f33fa4f1e4b3ee0431[0.0]</script>
<script src="lib/react-%s/react.production.min.js"></script>
<script src="lib/react-dom-%s/react-dom.production.min.js"></script>
<script>alert('hello')</script>
</head>
<body>
<script type="text/javascript" data-needs-render="">
(function() {
var container = new DocumentFragment();
ReactDOM.render(
Expand Down Expand Up @@ -115,7 +126,10 @@ def test_jsx_tags():
thisScript.after(container);
thisScript.removeAttribute('data-needs-render');
})();
</script>"""
</script>
</body>
</html>"""
% (react_ver, react_dom_ver, react_ver, react_dom_ver)
)

x = Foo(
Expand Down

0 comments on commit bde4d1b

Please sign in to comment.