04: Router
A two-page app using
SimpleRouterComponent. Shows the routes-dict shape, the 404 fallback, the permissiveget_layoutsignature, and aliasing (multiple paths mapping to the same component instance).
The script
from weaverlet.base import WeaverletComponent, WeaverletApp
from weaverlet.components import SimpleRouterComponent
from dash import html
class PageAComponent(WeaverletComponent):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def get_layout(self, pathname, hash, href, search):
return html.Div(f'hello from Page A!')
class PageBComponent(WeaverletComponent):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def get_layout(self, pathname, hash, href, search):
return html.Div(f'hello from Page B!')
class PageNotFoundComponent(WeaverletComponent):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def get_layout(self, pathname):
return html.Div(f'Page not found!')
page_a_component = PageAComponent()
page_b_component = PageBComponent()
not_found_page_component = PageNotFoundComponent()
routes = {
'/': page_a_component,
'/page_a': page_a_component,
'/page_b': page_b_component
}
router_component = SimpleRouterComponent(
routes=routes,
not_found_page_component=not_found_page_component
)
wapp = WeaverletApp(root_component=router_component)
wapp.app.run(port=8089)
Expected output
http://localhost:8089/→ "hello from Page A!"/page_a→ "hello from Page A!" (same instance, aliased)/page_b→ "hello from Page B!"- Any other path → "Page not found!"
Notes
routesis a regular Python dict mapping paths to component instances. The router matchespathnameagainst the keys.'/': page_a_componentand'/page_a': page_a_componentboth point to the samePageAComponentinstance. That's aliasing. Multiple paths can share one canonical wrapper, both in default mode and underkeep_mounted=True.- Routed components may declare any subset of
(pathname, hash, href, search)inget_layout.PageAComponentandPageBComponentdeclare the full set;PageNotFoundComponentdeclares onlypathname. The router introspects each signature and passes only matching kwargs. not_found_page_componentis required. No implicit fallback.- By default
keep_mounted=False: each route mounts on entry, unmounts on exit. For state preservation across navigation, see Example 14.
Try it locally
pip install weaverlet
python router_app.py
See also
SimpleRouterComponent: conceptSimpleRouterComponent: API referencekeep_mounted. Preserve state across navigation.