Skip to content

Commit d48ef21

Browse files
Add support for list flattening args
1 parent 2b413e0 commit d48ef21

File tree

3 files changed

+40
-3
lines changed

3 files changed

+40
-3
lines changed

pyhtml/__tag_base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def __init__(self, *children: Any, **properties: Any) -> None:
1818
"""
1919
Create a new tag instance
2020
"""
21-
self.children = list(children)
21+
self.children = util.flatten_list(list(children))
2222
"""Children of this tag"""
2323

2424
self.properties = util.filter_properties(properties)
@@ -34,7 +34,7 @@ def __call__(
3434
properties are based on this original tag, but with additional children
3535
appended and additional properties unioned.
3636
"""
37-
new_children = self.children + list(children)
37+
new_children = self.children + util.flatten_list(list(children))
3838
new_properties = self.properties | properties
3939

4040
return self.__class__(*new_children, **new_properties)

pyhtml/__util.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
44
Random helpful functions used elsewhere
55
"""
6-
from typing import Any
6+
from typing import Any, TypeVar
7+
8+
9+
T = TypeVar('T')
710

811

912
def increase_indent(text: list[str], amount: int) -> list[str]:
@@ -111,3 +114,18 @@ def render_children(children: list[Any], sep: str = ' ') -> list[str]:
111114
for ele in children:
112115
rendered.extend(render_inline_element(ele))
113116
return increase_indent(rendered, 2)
117+
118+
119+
def flatten_list(the_list: list[T | list[T]]) -> list[T]:
120+
"""
121+
Flatten a list by taking any list elements and inserting their items
122+
individually. Note that other iterables (such as str and tuple) are not
123+
flattened.
124+
"""
125+
result: list[T] = []
126+
for item in the_list:
127+
if isinstance(item, list):
128+
result.extend(item)
129+
else:
130+
result.append(item)
131+
return result

tests/basic_rendering_test.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,3 +122,22 @@ def test_format_through_repr():
122122
doc = html()
123123

124124
assert repr(doc) == "<html></html>"
125+
126+
127+
def test_flatten_element_lists():
128+
"""
129+
If a list of elements is given as a child element, each element should be
130+
considered as a child.
131+
"""
132+
doc = html([p("Hello"), p("world")])
133+
134+
assert repr(doc) == "\n".join([
135+
"<html>",
136+
" <p>",
137+
" Hello",
138+
" </p>",
139+
" <p>",
140+
" world",
141+
" </p>",
142+
"</html>",
143+
])

0 commit comments

Comments
 (0)