šŸ“£ Introducing Dash `/pages` - A Dash 2.x Feature Preview

@AnnMarieW Wow! I had to make some slight modifications because Iā€™m already importing over the dash_bootstrap_components as dbc. I basically had your dbc as dbc_css. The below code works! Wow, this actually makes the dropdown be transparent and change font with the theme! This is super neat! Thanks so much for sharing!

Also, let me know if I setup the init.py correctly. When i tried that with dash_labs I still get the keyerror. Thanks for the help!

import dash
import dash_bootstrap_components as dbc
import pages_plugin
from dash import Dash, dcc, html
from dash_bootstrap_templates import ThemeChangerAIO
import dash_labs as dl

# load_figure_template("bootstrap")

dbc_css = (
    "https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates@V1.0.1/dbc.min.css"
)

app = Dash(__name__, plugins=[pages_plugin], external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])
# app = Dash(__name__, plugins=[dl.plugins.pages], external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])

app.layout = dbc.Container(
    html.Div([
    html.H1('Manheim Capacity Model - Work in progress'),
    html.H2('Updated as of 11/17/2021 by John Kang'),
    dbc.Row(
        [
            dbc.Col(ThemeChangerAIO(aio_id="theme", radio_props={"value": dbc.themes.DARKLY}), width=2, ),
        ]
    ),
    html.Div(
        dcc.Link('Go back home', href=dash.page_registry['pages.home']['path'])
    ),

    html.Div([
        html.Div(dcc.Link(
            f"{page['name']} - {page['path']}",
            href=page['path']
        ))
        for page in dash.page_registry.values()
        if page['module'] != 'pages.not_found_404'
    ]),

    pages_plugin.page_container

]),
    className='dbc',
    fluid=True
)

if __name__ == '__main__':
    # app.run_server(debug=True)
    app.run_server(debug=True, use_reloader=False, host="localhost", port=8051)

Hey @johnkangw

Glad the dbc_css works for you (actually, thatā€™s how I recommend doing it -Iā€™ll update my previous post - which was wrong)

Iā€™m mystified about the key error. Can you provide a minimal example that reproduces the error?

Or one more thing to tryā€¦ when you use the dash-labs version, also delete this line:

import pages_plugin

@AnnMarieW Hi Ann, thanks for the suggestion. I modified the code to comment out the pages_plugin and it still gives me a keyerror even when I comment out the import pages_plugin (first try) and then commennt out the keyerror and the container (second try)
First try
Code:

import dash
import dash_bootstrap_components as dbc
# import pages_plugin
from dash import Dash, dcc, html
from dash_bootstrap_templates import ThemeChangerAIO
import dash_labs as dl

# load_figure_template("bootstrap")

dbc_css = (
    "https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates@V1.0.1/dbc.min.css"
)

# app = Dash(__name__, plugins=[pages_plugin], external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])
app = Dash(__name__, plugins=[dl.plugins.pages], external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])

app.layout = dbc.Container(
    html.Div([
    html.H1('Manheim Capacity Model - Work in progress'),
    html.H2('Updated as of 11/17/2021 by John Kang'),
    dbc.Row(
        [
            dbc.Col(ThemeChangerAIO(aio_id="theme", radio_props={"value": dbc.themes.DARKLY}), width=2, ),
        ]
    ),
    html.Div(
        dcc.Link('Go back home', href=dash.page_registry['pages.home']['path'])
    ),

    html.Div([
        html.Div(dcc.Link(
            f"{page['name']} - {page['path']}",
            href=page['path']
        ))
        for page in dash.page_registry.values()
        if page['module'] != 'pages.not_found_404'
    ]),

    pages_plugin.page_container

]),
    className='dbc',
    fluid=True
)

if __name__ == '__main__':
    # app.run_server(debug=True)
    app.run_server(debug=True, use_reloader=False, host="localhost", port=8007)

first try error:

Python 3.8.12 (default, Oct 12 2021, 03:01:40) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.29.0 -- An enhanced Interactive Python. Type '?' for help.
PyDev console: using IPython 7.29.0
Python 3.8.12 (default, Oct 12 2021, 03:01:40) [MSC v.1916 64 bit (AMD64)] on win32
runfile('C:/Users/Jkang1/Cox Automotive/Recon Industrial Engineering Team - General/Capacity Model/main_python_files/app.py', wdir='C:/Users/Jkang1/Cox Automotive/Recon Industrial Engineering Team - General/Capacity Model/main_python_files')
Traceback (most recent call last):
  File "C:\Anaconda3\envs\Capacity_venv\Lib\site-packages\IPython\core\interactiveshell.py", line 3444, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-a2b8dda0f18e>", line 1, in <module>
    runfile('C:/Users/Jkang1/Cox Automotive/Recon Industrial Engineering Team - General/Capacity Model/main_python_files/app.py', wdir='C:/Users/Jkang1/Cox Automotive/Recon Industrial Engineering Team - General/Capacity Model/main_python_files')
  File "C:\Program Files\JetBrains\PyCharm 2021.2.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2021.2.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Jkang1/Cox Automotive/Recon Industrial Engineering Team - General/Capacity Model/main_python_files/app.py", line 27, in <module>
    dcc.Link('Go back home', href=dash.page_registry['pages.home']['path'])
KeyError: 'pages.home' ```

I noticed that if I comment out the dcc.Link and the container (see code below) the dash app will run but will be in an error state:
Second try

import dash
import dash_bootstrap_components as dbc
# import pages_plugin
from dash import Dash, dcc, html
from dash_bootstrap_templates import ThemeChangerAIO
import dash_labs as dl

# load_figure_template("bootstrap")

dbc_css = (
    "https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates@V1.0.1/dbc.min.css"
)

# app = Dash(__name__, plugins=[pages_plugin], external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])
app = Dash(__name__, plugins=[dl.plugins.pages], external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])

app.layout = dbc.Container(
    html.Div([
    html.H1('Manheim Capacity Model - Work in progress'),
    html.H2('Updated as of 11/17/2021 by John Kang'),
    dbc.Row(
        [
            dbc.Col(ThemeChangerAIO(aio_id="theme", radio_props={"value": dbc.themes.DARKLY}), width=2, ),
        ]
    ),
    # html.Div(
    #     dcc.Link('Go back home', href=dash.page_registry['pages.home']['path'])
    # ),

    html.Div([
        html.Div(dcc.Link(
            f"{page['name']} - {page['path']}",
            href=page['path']
        ))
        for page in dash.page_registry.values()
        if page['module'] != 'pages.not_found_404'
    ]),

    # pages_plugin.page_container

]),
    className='dbc',
    fluid=True
)

if __name__ == '__main__':
    # app.run_server(debug=True)
    app.run_server(debug=True, use_reloader=False, host="localhost", port=8007)

The error I receive when I comment out the container (when I can load the app):
Second try error

ā›‘ļø
ID not found in layout
10:28:19 AM
Attempting to connect a callback Input item to component:
  "_pages_plugin_location"
but no components with that id exist in the layout.

If you are assigning callbacks to components that are
generated by other callbacks (and therefore not in the
initial layout), you can suppress this exception by setting
`suppress_callback_exceptions=True`.
This ID was used in the callback(s) for Output(s):
  _pages_plugin_dummy.children
  _pages_plugin_content.children
  _pages_plugin_content.children

My home.py code is standard:

import dash
from dash import html

dash.register_page(
	__name__,
	path='/',
	name='Capacity Model homepage',
	description='Welcome to my app',
	order=0,
	redirect_from=['/old-home-page', '/v2'],
	extra_template_stuff='yup'
)

layout = html.Div([
    html.H1('Homepage for the app'),
    html.H2('Notes to be populated soon')
])type or paste code here```

@johnkangw

Sorry I didnā€™t see this before, but when you use dash-labs , instead of pages_plugin.page_container, you need to use:

dl.plugins.page_container

@AnnMarieW Thanks so much! I made the changes but i still receive the key error.

  File "C:/Users/Jkang1/Cox Automotive/Recon Industrial Engineering Team - General/Capacity Model/main_python_files/app.py", line 26, in <module>
    dcc.Link('Go back home', href=dash.page_registry['pages.home']['path'])
KeyError: 'pages.home'

I tried commenting out line 25-27 to get rid of the error, and it goes away but then the app just loads to a 404 page. Maybe something is going on with my folder structure such that the dash_labs code canā€™t find my folder?

import dash
import dash_bootstrap_components as dbc
import pages_plugin
from dash import Dash, dcc, html
from dash_bootstrap_templates import ThemeChangerAIO
import dash_labs as dl
# load_figure_template("bootstrap")

dbc_css = (
    "https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates@V1.0.1/dbc.min.css"
)

# app = Dash(__name__, plugins=[pages_plugin], external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])
app = Dash(__name__, plugins=[dl.plugins.pages], external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css])

app.layout = dbc.Container(
    html.Div([
    html.H1('Manheim Capacity Model - Work in progress'),
    html.H2('Updated as of 11/17/2021 by John Kang'),
    dbc.Row(
        [
            dbc.Col(ThemeChangerAIO(aio_id="theme", radio_props={"value": dbc.themes.DARKLY}), width=2, ),
        ]
    ),
    # html.Div(
    #     dcc.Link('Go back home', href=dash.page_registry['pages.home']['path'])
    # ),

    html.Div([
        html.Div(dcc.Link(
            f"{page['name']} - {page['path']}",
            href=page['path']
        ))
        for page in dash.page_registry.values()
        if page['module'] != 'pages.not_found_404'
    ]),

    # pages_plugin.page_container
    dl.plugins.page_container



]),
    className='dbc',
    fluid=True
)

if __name__ == '__main__':
    # app.run_server(debug=True)
    app.run_server(debug=True, use_reloader=False, host="localhost", port=8009)

project folder structure
A snapshot of my project folder structure (Iā€™m using PyCharm).
The bottom of my project folder (shows the pages plugin file):
rest of project folder

This looks to be an awesome upcoming addition to Dash. Quick question, is there a way to get this to work with long_callback or some form of flask-caching since that is still bound to app? Iā€™m guessing you would need to go back to having both an index.py and app.py file to avoid the circular imports?

2 Likes

Hi @bigmike

Itā€™s true that @callback does not yet support long_callback.

Hereā€™s one workaround I tried: I put the layouts that include the long_callbacks in pages/ and the @app.long_callback s in the app.py file.

It makes the index.py file unnecessary and all the new functionality of Dash pages/ still worked.

@chriddyp is there a better way?

2 Likes

Thatā€™s probably the best way for now. The ultimate solution is to have another form of long_callback that doesnā€™t require the app object.

Would love if this feature was included in the 2.1 release as well (plus support for even more than just one layer deep as well if possible because I have a pretty massive application that Iā€™m trying to convert to Dash and it currently has 3 levels of pages and the additional hierarchy would be very much appreciated).

Hey @dash-beginner - Iā€™m glad you like this feature, and I hope this will be ready for Dash 2.1, but in the meantime itā€™s available in Dash Labs. See more info here: šŸ“£ Dash Labs 1.0.0: Dash `pages` - An easier way to make multi-page apps

The nested folders feature is available in Dash-Labs. If you get a chance to try it, please let us know how it works for you. It will be faster to make fixes and enhancements in Dash Labs rather than wait for the official Dash release schedule.

3 Likes

This solved my issue. Really appreciate the reply!

1 Like

:mega: Iā€™m pleased to announce the release of Dash Labs V1.0.1

pip install dash-labs -U

This release includes two bug fixes:

  • #59 Fixed bug that prevented order prop from changing the order of the modules in dash.page_registry
  • #55 Fixed bug that prevented multipage apps from working in windows

Big thanks to @johnkangw for reporting the Windows bug and for doing the pull request to fix it! :medal_sports:

See more about how to use this feature in Dash Labs here: šŸ“£ Dash Labs 1.0.0: Dash `pages` - An easier way to make multi-page apps

1 Like

If a page needs a static asset like an image in the layout, how would you recommend doing this when the asset is in appā€™s assets folder?

i.e. replacing the following:

html.Img(id=ā€œpage_iconā€, src=app.get_asset_url(ā€œpage_icon.pngā€))

Hi @jgaewsky and welcome to the Dash community :slight_smile:

The assets folder works with pages/. You can see an example of images added to an app in dash-labs here: dash-labs/10-MultiPageDashApp-MetaTags.md at main Ā· plotly/dash-labs Ā· GitHub

See the demo app here: dash-labs/docs/demos/multi_page_meta_tags at main Ā· plotly/dash-labs Ā· GitHub

Thanks, @chriddyp and @AnnMarieW! The pages feature is an excellent addition and makes Dash even better!

I was wondering if it is possible to set up an app structure that allows multiple sub pages per page. The idea is to navigate the pages using a navigation bar at the top, and to add a second navigation bar whenever a page has sub pages. I came up with the following app structure and would like to ask whether you think this is a reasonable approach. For each of the pages, I have a folder containing page-specific stuff: layout, callbacks etc. In my example, page 2 has sub pages:

-- pages
   |-- home
       |-- home.py
   |-- page_1
       |-- page_1.py
   |-- page_2
       |-- sub_item_1
            |-- sub_item_1.py
       |-- sub_item_2
            |-- sub_item_2.py
       |-- submenu.py
       |-- page_2.py
   |-- other pages...
   |-- app.py

In principle, I got this to work with the following implementation, but I am not sure if this is the best approach and would appreciate any kind of feedback. I only add navigation links to the navigation bar at the top when ā€˜subā€™ is not a sub string of the ā€˜moduleā€™ value of a page.

app.py:

import dash
import dash_labs as dl
import dash_bootstrap_components as dbc

from dash import html, Input, Output, State

app = dash.Dash( __name__, plugins=[dl.plugins.pages], external_stylesheets=[dbc.themes.BOOTSTRAP])

navbar = dbc.Navbar(
    dbc.Container([
        html.A(dbc.Row(
            dbc.Col(dbc.NavbarBrand("MyApp", className="ms-2")),
                align="center",
                className="g-0",
        ),
        href="/",
        style={"textDecoration": "none"},
        ),
        dbc.Row([
            dbc.NavbarToggler(id="navbar-toggler"),
            dbc.Collapse(
                dbc.Nav([
                    dbc.NavItem(dbc.NavLink(page['name'], href=page['path'], active="exact")) for page in dash.page_registry.values() if page["module"] != "pages.not_found_404" and "sub" not in page["module"]
                ],
                className="w-100",
                ),
            id="navbar-collapse",
            is_open=False,
            navbar=True,
            ),
        ],
        className="flex-grow-1",
        ),
    ],
    fluid=True,
    ),
    dark=True,
    color="dark",
    fixed="top",
    sticky=True
)

app.layout = html.Div([navbar, dl.plugins.page_container]) 

@app.callback(
    Output("navbar-collapse", "is_open"),
    [Input("navbar-toggler", "n_clicks")],
    [State("navbar-collapse", "is_open")],
)
def toggle_navbar_collapse(n, is_open):
    if n:
        return not is_open
    return is_open

if __name__ == "__main__":
    app.run_server(debug=True)

home.py:

import dash
from dash import html
import dash_bootstrap_components as dbc

dash.register_page(__name__, path="/", order=1)

content = [html.H2("Home")]

layout = html.Div([
   dbc.Row(
       dbc.Col(content, width={"size": 8, "offset": 1}),
       align="center"
   )
])

page_2.py:

import dash
from dash import dcc, html
from .submenu import sidebar

dash.register_page(__name__, path="/page_2", order=2)

content = html.Div([html.H2("Page 2")])

layout = html.Div([sidebar, content])

Creating the submenu automatically from the page registry does not work, so I am creating it manually. I assume, page 2 is not fully registered here, but creating it in app.py and importing it from there is not possible because it would be a circular import.
submenu.py:

import dash_bootstrap_components as dbc
from dash import html

sidebar = html.Div([
    dbc.Nav([  # this works
        dbc.NavLink("Sub Item 1", href="/page_2/item_1", active="partial"),
        dbc.NavLink("Sub Item 2", href="/page_2/item_2", active="partial")
    ], vertical=True, pills=True),

    # dbc.Nav([  # this does not work
    #     dbc.NavLink(page['name'], href=page['path'], active="exact") for page in dash.page_registry.values() if page["module"] != "pages.not_found_404" and "page_2.sub" in page["module"]
    # ], vertical=True, pills=True)


], style={"position": "fixed", "padding": "1rem 1rem", "background-color": "#f8f9fa", "height": "100vh"})

sub_item_1.py:

import dash
from dash import html
from ..submenu import sidebar

dash.register_page(__name__, path="/page_2/item_1", order=1)

content = html.Div([html.H2("Page 2 - Item 1")])

layout = html.Div([sidebar, content])

sub_item_2.py:

import dash
from dash import html
from ..submenu import sidebar

dash.register_page(__name__, path="/page_2/item_2", order=1)

content = html.Div([html.H2("Page 2 - Item 2")])

layout = html.Div([sidebar, content])

With this setup, the ā€˜activeā€™ style of the dbc.NavLinks in the navigation bar at the top does not work any more. Any ideas on how to use this feature? Any feedback would be highly appreciated!

1 Like

Hey @mawe Iā€™m glad you like pages/ :slight_smile:

Yes, itā€™s possible to have nested folders within the pages folder. You can find an example here: dash-labs/09-MultiPageDashApp-NestedFolders.md at main Ā· plotly/dash-labs Ā· GitHub

I think your approach for adding the navigation to the top bar is good, and you found a nice workaround for having a conditional side-bar per page. Itā€™s true that in this case itā€™s too early to use the conveinence of looping through the dash.page_registry because it hasnā€™t finished building yet. Adding the links directly is a good solution.

Setting active="partial" instead of active="exact" in the header NavLink should make the active style work. However, you probably need to have a different path for the Home page because the current home page path of "/" will show as active if you set it to active="partial"

4 Likes

This piece of the pages/ design concerns me a bit. I wonder how we could get around this.

One idea: what if dash layouts could accept a function and that function would be called later upon serialization and whatever would be returned would be serialized. So you could have like:

header = lambda: [dcc.Link(p) for p in dash.page_registry]
1 Like

Hey @mawe

@chriddyp had a good idea. I changed the layouts and the sidebar to functions and it worked :partying_face:

Could you give this a try?

This is the submenu.py. The sidebar is now a function:

import dash_bootstrap_components as dbc
import dash

def make_sidebar():
    return dbc.Nav([  
          dbc.NavLink(page['name'], href=page['path'], active="exact") for page in dash.page_registry.values() if  "page_2.sub" in page["module"]
      ], vertical=True, pills=True)

This is page2.py
(sub_item_1.py and sub_item_2.py are similar. Import the make_sidebar function, and add it to the layout. Note that the layout is also now a function)

import dash
from dash import html
from .submenu import make_sidebar

dash.register_page(__name__, path="/page_2", order=2)

content = html.Div([html.H2("Page 2")])

def layout():
    return html.Div([make_sidebar(), content])


4 Likes

Hi @AnnMarieW!

Your solution for the sidebar navigation works beautifully!

Also, I got the active style in the main navigation bar at the top to work by simply checking the current page in app.py and setting the active style accordingly:

dbc.NavItem(dbc.NavLink(page['name'], href=page['path'], active="exact" if page["path"] == "/" else "partial")) for page in dash.page_registry.values() if page["module"] != "pages.not_found_404" and "sub" not in page["module"]
4 Likes