Skip to content

Commit

Permalink
fix list rendering for single elements (#44)
Browse files Browse the repository at this point in the history
* fix list rendering for single elements

* bump version
  • Loading branch information
ogrodnek authored Sep 11, 2024
1 parent 4d790da commit c52144b
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ packages = [
{ include = "pyview" },
]

version = "0.0.23"
version = "0.0.24"
description = "LiveView in Python"
authors = ["Larry Ogrodnek <[email protected]>"]
license = "MIT"
Expand Down
17 changes: 11 additions & 6 deletions pyview/vendor/ibis/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,14 @@ class PartsComprehension:
def __init__(self, parts: list[Part]):
self.parts = parts

def render_parts(self) -> dict[str, Any]:
def render_parts(self) -> Union[dict[str, Any], str]:
if len(self.parts) == 0:
return ""

if len(self.parts) == 1:
if isinstance(self.parts[0], PartsTree) and self.parts[0].is_empty():
return ""

def render(p: Part) -> Any:
if isinstance(p, str):
return p
Expand All @@ -38,17 +42,13 @@ def add_static(self, s: str):
self.statics.append(s)

def add_dynamic(self, d: Union[Part, list[Part]]):

if len(self.statics) < len(self.dynamics) + 1:
self.statics.append("")

if isinstance(d, str):
self.dynamics.append(d)
elif isinstance(d, list):
if len(d) > 1:
self.dynamics.append(PartsComprehension(d))
elif len(d) == 1:
self.dynamics.append(d[0].flatten())
self.dynamics.append(PartsComprehension(d))
else:
self.dynamics.append(d.flatten())

Expand Down Expand Up @@ -85,3 +85,8 @@ def render_parts(self) -> dict[str, Any]:
resp[f"{i}"] = dynamic.render_parts()

return resp

def is_empty(self) -> bool:
return len(self.dynamics) == 0 and (
len(self.statics) == 0 or (len(self.statics) == 1 and self.statics[0] == "")
)
15 changes: 15 additions & 0 deletions tests/vendor/ibis/test_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,21 @@ def test_loop():
}
assert a.render(d) == "<div><span>Larry</span><span>Sally</span></div>"


def test_loop_single_element():
a = Template("<div>{% for v in users %}<span>{{v.name}}</span>{% endfor %}</div>")
d = {"users": [{"name": "Larry"}]}

assert a.tree(d) == {
"s": ["<div>", "</div>"],
"0": {"s": ["<span>", "</span>"], "d": [["Larry"]]},
}
assert a.render(d) == "<div><span>Larry</span></div>"


def test_loop_empty():
a = Template("<div>{% for v in users %}<span>{{v.name}}</span>{% endfor %}</div>")

d = {"users": []}
assert a.tree(d) == {"s": ["<div>", "</div>"], "0": ""}
assert a.render(d) == "<div></div>"
Expand Down

0 comments on commit c52144b

Please sign in to comment.