Replies: 6 comments 9 replies
-
React has useContext etc for this(https://react.dev/learn/passing-data-deeply-with-context). I have been thinking of doing something similar for htpy but I think using the builtin contextvars module (https://docs.python.org/3/library/contextvars.html) solves this without doing anything else in htpy: import contextvars
import htpy as h
color_scheme = contextvars.ContextVar("color_scheme", default="light")
print(h.div(class_=f"color-scheme-{color_scheme.get()}")["Hi"])
color_scheme.set("dark")
print(h.div(class_=f"color-scheme-{color_scheme.get()}")["Hi"]) result:
So it is basically global state but managed a bit nicer. By using contextvars, it would be thread/async safe and works with typing. set/reset can be used in a view/middleware to set the values. Does that work for you? In that case we should definitely document this pattern. |
Beta Was this translation helpful? Give feedback.
-
(Did not yet had the need for this myself so I have not used it.) |
Beta Was this translation helpful? Give feedback.
-
I played with making it possible to pass contexts similar to how React does it, what do you think about #48 ? |
Beta Was this translation helpful? Give feedback.
-
Ohh! Thats very nice of you 😃 Could you write up an example how this would be used in a scenario where I have multiple nested components? Example:I have a theme (str) and a side_menu_open (bool).
|
Beta Was this translation helpful? Give feedback.
-
Thanks for the explanation! I agree that you probably don't want hooks, etc. in htpy. Love the decorator yes 👏🏻! |
Beta Was this translation helpful? Give feedback.
-
This is released as part of htpy 24.8.2, give it a try and let me know how it goes! |
Beta Was this translation helpful? Give feedback.
-
Having to pass state down from the
body -> side_menu -> current_tab -> list_of_folders -> folder -> list_of_items -> item
isn't fun.How do you solve this?
Beta Was this translation helpful? Give feedback.
All reactions