From c52144b1234f87a93755db3c0c06f72755855493 Mon Sep 17 00:00:00 2001 From: Larry Ogrodnek Date: Tue, 10 Sep 2024 21:48:09 -0400 Subject: [PATCH] fix list rendering for single elements (#44) * fix list rendering for single elements * bump version --- pyproject.toml | 2 +- pyview/vendor/ibis/tree.py | 17 +++++++++++------ tests/vendor/ibis/test_template.py | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c8eb311..32faf1d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ packages = [ { include = "pyview" }, ] -version = "0.0.23" +version = "0.0.24" description = "LiveView in Python" authors = ["Larry Ogrodnek "] license = "MIT" diff --git a/pyview/vendor/ibis/tree.py b/pyview/vendor/ibis/tree.py index 1be22fa..1f92b8b 100644 --- a/pyview/vendor/ibis/tree.py +++ b/pyview/vendor/ibis/tree.py @@ -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 @@ -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()) @@ -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] == "") + ) diff --git a/tests/vendor/ibis/test_template.py b/tests/vendor/ibis/test_template.py index 1a5ec75..18772d5 100644 --- a/tests/vendor/ibis/test_template.py +++ b/tests/vendor/ibis/test_template.py @@ -104,6 +104,21 @@ def test_loop(): } assert a.render(d) == "
LarrySally
" + +def test_loop_single_element(): + a = Template("
{% for v in users %}{{v.name}}{% endfor %}
") + d = {"users": [{"name": "Larry"}]} + + assert a.tree(d) == { + "s": ["
", "
"], + "0": {"s": ["", ""], "d": [["Larry"]]}, + } + assert a.render(d) == "
Larry
" + + +def test_loop_empty(): + a = Template("
{% for v in users %}{{v.name}}{% endfor %}
") + d = {"users": []} assert a.tree(d) == {"s": ["
", "
"], "0": ""} assert a.render(d) == "
"