How to define callbacks within layout function in multi-page dash app?

I developed multi-page dash app with use_pages set as True in app.py.

in pages/detail.py file, the page is registered with path_template so as to get the <product_id> from url.
dash.register_page(__name__, path_template="/details/<product_id>")

And inside the layout(product_id:str) function, i need to return the component generated using <product_id>, which also needs to define some callbacks to function.

details.py


dash.register_page(__name__, path_template="/details/<product_id>")

def layout(product_id:str = "", **kwargs):
    layout = html.Div([
        html.H3(children = 'Product_id: {}'.format(product_id)),
        html.H5(children = 'Output', id=f"output-{product_id}"),
        dcc.Input(value='Example', id=f"output-{product_id}")
    ])

    @callback(
        Output(f"output-{product_id}"', 'children'),
        Input(f"output-{product_id}", 'value'),
    )
    def update_output(input_str:str):
        return input_str

    return layout

But the problem is that when i tried to define @callback inside the layout function, it did not function at all.

How can i define callbacks specific to components in layout function?

Hello @eshark9312,

Welcome to the community!

Callbacks need to be declared at the app spin up, so you’ll need to just have the callbacks defined on the script level and not inside of the function.

Otherwise, you can call the function at the end of the script with the same effect.

1 Like

thanks for your reply, but i need to generate the component with path_variable, <product-id> in my case.
And the problem is that i can refer to path_variable only in layout function.
Then, my question is how to get the path_variable inside the app spin?

Do you have any idea to get path_variable in script level?

do you have any idea to get the path_variable in script level?

You can use a dcc.store and store the path variable there, or use the location href / pathname and pull the variable by parsing it out.

These are just a couple of options. I think there may be a couple more ways too. But these should get the job done.

Pattern-matching callbacks might be a solution. You can then define one pattern-matching callback across all product-ids, without needing to know what the product-ids are when you write the callback.

Thanks for your comment.
I was able to solve the issue with Pattern-Matching Callbacks.