Reputation: 35
I am trying to make a clientside callback in Plotly Dash where a JavaScript script will be executed. I have a Python variable defined somewhere else in the script and now I want to pass that variable to the clientside callback where I have my script. Here is a snippet of the code:
python_variable = 'string or some variable'
app.clientside_callback(
"""
function(n_clicks, user_input) {
if (n_clicks){
alert(%{user_input} + %{python_variable});
}
}
""",
Output('dummy_div', 'children'),
[Input('btn', 'n_clicks'),
Input('user_input', value)]
I do not know how to put my python_variable in a dcc.Store as I load variables during page load (have no callback for this). Is it possible to add my Python variable to my clientside callback function?
Upvotes: 1
Views: 2851
Reputation: 15462
You can directly pass the variable to the data
property of a dcc.Store
component in the layout.
Then you can just add the Store
components' data
property to the callback as a State
.
MWE:
from dash import Dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
python_variable = "string or some variable"
app = Dash(__name__)
app.layout = html.Div(
[
dcc.Input(id="input", value="", type="text"),
html.Div(id="output"),
dcc.Store(id="store", data=python_variable),
]
)
app.clientside_callback(
"""
function(input, python_variable) {
return `${python_variable}: ${input}`
}
""",
Output("output", "children"),
Input("input", "value"),
State("store", "data"),
)
if __name__ == "__main__":
app.run_server()
Upvotes: 3