How to perform more operations on Vars #2304
PasqualePuzio
announced in
General
Replies: 1 comment 2 replies
-
you should be able to make a standalone function that accepts a Var and returns a Var, just like the existing operations defined in def replace(value: rx.Var, pattern: rx.Var | str, replacement: rx.Var | str) -> rx.Var:
pattern = rx.Var.create_safe(json.dumps(pattern)) if isinstance(pattern, str) else pattern
replacement = rx.Var.create_safe(json.dumps(replacement)) if isinstance(replacement, str) else replacement
return value._replace(
_var_name=f"{value._var_name}.replace({pattern._var_full_name}, {replacement._var_full_name})",
_var_is_string=False,
merge_var_data=rx.vars.VarData.merge(pattern._var_data, replacement._var_data),
) Full example: import reflex as rx
import json
class State(rx.State):
"""The app state."""
who: str = "Reflex"
what: str = "lex"
then_what: str = "lax"
def replace(value: rx.Var, pattern: rx.Var | str, replacement: rx.Var | str) -> rx.Var:
pattern = rx.Var.create_safe(json.dumps(pattern)) if isinstance(pattern, str) else pattern
replacement = rx.Var.create_safe(json.dumps(replacement)) if isinstance(replacement, str) else replacement
return value._replace(
_var_name=f"{value._var_name}.replace({pattern._var_full_name}, {replacement._var_full_name})",
_var_is_string=False,
merge_var_data=rx.vars.VarData.merge(pattern._var_data, replacement._var_data),
)
def index() -> rx.Component:
return rx.fragment(
rx.color_mode_button(rx.color_mode_icon(), float="right"),
rx.vstack(
rx.heading(
replace(
"Welcome to " + State.who,
State.what,
State.then_what
),
font_size="2em"
),
spacing="1.5em",
font_size="2em",
padding_top="10%",
),
)
# Add state and page to the app.
app = rx.App()
app.add_page(index)
app.compile() Compiles out to code that looks like export function Heading_5fd82e2d9f99fa97eb6ad5e62f3da6ef () {
const state__state = useContext(StateContexts.state__state)
return (
<Heading sx={{"fontSize": "2em"}}>
{("Welcome to " + state__state.who).replace(state__state.what, state__state.then_what)}
</Heading>
)
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I was wondering if there's any way to implement one or more operations on a specific Var.
For instance, we would like to be able to perform a replace operation on a string but we didn't figure out a way to do so. The only solution we have right now is to store result of the replace operation in another var.
Beta Was this translation helpful? Give feedback.
All reactions