improve foreach behavior with strings

This commit is contained in:
Khaleel Al-Adhami 2025-02-04 16:35:38 -08:00
parent c3ac051bbb
commit 4ed9b8ff7c

View File

@ -54,9 +54,10 @@ class Foreach(Component):
TypeError: If the render function is a ComponentState. TypeError: If the render function is a ComponentState.
UntypedVarError: If the iterable is of type Any without a type annotation. UntypedVarError: If the iterable is of type Any without a type annotation.
""" """
from reflex.vars.object import ObjectVar from reflex.vars import ArrayVar, ObjectVar, StringVar
iterable = LiteralVar.create(iterable) iterable = LiteralVar.create(iterable)
if iterable._var_type == Any: if iterable._var_type == Any:
raise ForeachVarError( raise ForeachVarError(
f"Could not foreach over var `{iterable!s}` of type Any. " f"Could not foreach over var `{iterable!s}` of type Any. "
@ -75,6 +76,15 @@ class Foreach(Component):
if isinstance(iterable, ObjectVar): if isinstance(iterable, ObjectVar):
iterable = iterable.entries() iterable = iterable.entries()
if isinstance(iterable, StringVar):
iterable = iterable.split()
if not isinstance(iterable, ArrayVar):
raise ForeachVarError(
f"Could not foreach over var `{iterable!s}` of type {iterable._var_type}. "
"See https://reflex.dev/docs/library/dynamic-rendering/foreach/"
)
component = cls( component = cls(
iterable=iterable, iterable=iterable,
render_fn=render_fn, render_fn=render_fn,