Closed yahiakala closed 2 days ago
I'd strongly recommend repacing your navigation links with the NavLink
components from routing
This eliminates a bunch of code:
But to keep existing code as is it's possible to add on_navigation
handling using the tools available in the router
here's a demo:
https://anvil.works/build#clone:YJO4ZDVBJRIY4BQZ=7CTS4MGWCF3MQYM4PTXQLFBC
from ._anvil_designer import MainTemplate
from routing import router
class Main(MainTemplate):
def __init__(self, **properties):
self.links = {"/": self.home_nav, "/about": self.about_nav}
self.init_components(**properties)
def on_navigate(self, **event_args):
context = router.get_routing_context()
for path, link in self.links.items():
if path == context.path:
link.role = "selected"
else:
link.role = None
def home_nav_click(self, **event_args):
router.navigate("/")
def about_nav_click(self, **event_args):
router.navigate("/about")
def form_show(self, **event_args):
router.add_event_handler("navigate", self.on_navigate)
self.on_navigate()
def form_hide(self, **event_args):
router.remove_event_handler("navigate", self.on_navigate)
Looks like I haven't documented this yet so i'll add this to the docs and also add this in the migration guide for hash routing
Thanks, all good now. Switched to nav links
Is your feature request related to a problem? Please describe. I want to migrate from anvil_extras and one of the last pieces is the on_navigation method in the main router form, documented here:
https://anvil-extras.readthedocs.io/en/latest/guides/modules/routing.html#on-navigation-example
Describe the solution you'd like I'm fine with any solution, including a method defined in a route class. Kind of like how we have a before_load method in the route class.
Describe alternatives you've considered I have put the code in the nav_click method in the template form, but this is not ideal as I want the on_navigation code to be executed any time a route is loaded. before_load doesn't really work since I need to access components in the form.
I am considering making a PR for this issue Yes