Search code examples
pythonplotlyplotly-dashdashboard

Is it possible to register Dash pages from an external module?


I have an existing Dash app which essentially implements the new Dash pages functionality with some in house code.

Our "pages" are in a separate repo which is packaged separately from our Dash server package (we extend some of the base Dash server functionality as well).

I'm beginning to investigate refactoring our application to take advantage of the routing and other improvements that come "out of the box" with Dash Pages.

As far as I can tell, you can specify a directory as the location of your Pages:

import dash

app = Dash(__name__, use_pages=True, pages_folder="/some/dir")

But I see no documentation of dynamically loading Pages from an external module, is this possible? If so, does any one have examples to share?

Thank you.


Solution

  • Ok I think I figured it out, here is a toy example:

    app.py
    /modules
      foo.py
      home.py
    

    app.py

    from dash import Dash, html, dcc
    import dash
    from modules import home, foo
    
    app = Dash(__name__, use_pages=True, pages_folder="")  # ignore local folder requirement
    dash.register_page(home.__name__, path="/", layout=home.layout)  # give it layout explicitly
    dash.register_page(foo.__name__, path="/foo", layout=foo.layout)
    
    app.layout = html.Div([
        html.H1('Multi-page app with Dash Pages'),
        html.Div(
            [
                html.Div(
                    dcc.Link(
                        f"{page['name']} - {page['path']}", href=page["relative_path"]
                    )
                )
                for page in dash.page_registry.values()
            ]
        ),
        dash.page_container
    ])
    
    
    if __name__ == '__main__':
        app.run_server()
    

    home.py

    from dash import html
    
    layout = html.Div(children=[
        html.H1(children='This is our Home page'),
    ])
    

    foo.py

    from dash import html
    
    layout = html.Div(children=[
        html.H1(children='This is a page about: foo'),
    ])