Skip to content

Commit b3b79a6

Browse files
authored
improve foreach behavior with strings (#4751)
* improve foreach behavior with strings * add a defensive guard before giving up * add integration tests
1 parent ab558ce commit b3b79a6

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

reflex/components/core/foreach.py

+12-2
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,10 @@ def create(
5454
TypeError: If the render function is a ComponentState.
5555
UntypedVarError: If the iterable is of type Any without a type annotation.
5656
"""
57-
from reflex.vars.object import ObjectVar
57+
from reflex.vars import ArrayVar, ObjectVar, StringVar
58+
59+
iterable = LiteralVar.create(iterable).guess_type()
5860

59-
iterable = LiteralVar.create(iterable)
6061
if iterable._var_type == Any:
6162
raise ForeachVarError(
6263
f"Could not foreach over var `{iterable!s}` of type Any. "
@@ -75,6 +76,15 @@ def create(
7576
if isinstance(iterable, ObjectVar):
7677
iterable = iterable.entries()
7778

79+
if isinstance(iterable, StringVar):
80+
iterable = iterable.split()
81+
82+
if not isinstance(iterable, ArrayVar):
83+
raise ForeachVarError(
84+
f"Could not foreach over var `{iterable!s}` of type {iterable._var_type}. "
85+
"See https://reflex.dev/docs/library/dynamic-rendering/foreach/"
86+
)
87+
7888
component = cls(
7989
iterable=iterable,
8090
render_fn=render_fn,

tests/integration/test_var_operations.py

+10
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,14 @@ def index():
628628
),
629629
id="dict_in_foreach3",
630630
),
631+
rx.box(
632+
rx.foreach("abcdef", lambda x: rx.text.span(x + " ")),
633+
id="str_in_foreach",
634+
),
635+
rx.box(
636+
rx.foreach(VarOperationState.str_var1, lambda x: rx.text.span(x + " ")),
637+
id="str_var_in_foreach",
638+
),
631639
rx.box(
632640
rx.foreach(
633641
VarOperationState.people,
@@ -844,6 +852,8 @@ def test_var_operations(driver, var_operations: AppHarness):
844852
("dict_in_foreach1", "a1b2"),
845853
("dict_in_foreach2", "12"),
846854
("dict_in_foreach3", "1234"),
855+
("str_in_foreach", "a b c d e f"),
856+
("str_var_in_foreach", "f i r s t"),
847857
("typed_dict_in_foreach", "Hello Alice33Hello Bob28"),
848858
]
849859

0 commit comments

Comments
 (0)