cond.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Create a list of components from an iterable."""
  2. from __future__ import annotations
  3. from typing import Any, Optional
  4. from pynecone.components.component import Component
  5. from pynecone.components.layout.fragment import Fragment
  6. from pynecone.components.tags import CondTag, Tag
  7. from pynecone.var import Var
  8. class Cond(Component):
  9. """Render one of two components based on a condition."""
  10. # The cond to determine which component to render.
  11. cond: Var[Any]
  12. # The component to render if the cond is true.
  13. comp1: Component
  14. # The component to render if the cond is false.
  15. comp2: Component
  16. # Whether the cond is within another cond.
  17. is_nested: bool = False
  18. @classmethod
  19. def create(
  20. cls, cond: Var, comp1: Component, comp2: Optional[Component] = None
  21. ) -> Cond:
  22. """Create a conditional component.
  23. Args:
  24. cond: The cond to determine which component to render.
  25. comp1: The component to render if the cond is true.
  26. comp2: The component to render if the cond is false.
  27. Returns:
  28. The conditional component.
  29. """
  30. from pynecone.components.layout.foreach import Foreach
  31. if comp2 is None:
  32. comp2 = Fragment.create()
  33. if isinstance(comp1, Foreach):
  34. comp1 = Fragment.create(comp1)
  35. if isinstance(comp2, Foreach):
  36. comp2 = Fragment.create(comp2)
  37. if isinstance(comp1, Cond):
  38. comp1.is_nested = True
  39. if isinstance(comp2, Cond):
  40. comp2.is_nested = True
  41. return cls(
  42. cond=cond,
  43. comp1=comp1,
  44. comp2=comp2,
  45. children=[comp1, comp2],
  46. ) # type: ignore
  47. def _render(self) -> Tag:
  48. return CondTag(
  49. cond=self.cond,
  50. true_value=self.comp1.render(),
  51. false_value=self.comp2.render(),
  52. is_nested=self.is_nested,
  53. )