Params

The path may contain one or more path parameters, denoted by the : character, e.g. /authors/:id.

from routing.router import Route

class AuthorRoute(Route):
    path = "/authors/:id"
    form = "Pages.Author"

When a user navigates to /authors/123, the routing context will include the path params {"id": 123}.

from ._anvil_designer import AuthorTemplate
from routing.router import RoutingContext

class Author(AuthorTemplate):
    def __init__(self, routing_context: RoutingContext, **properties):
        self.routing_context = routing_context
        self.author = anvil.server.call("get_author", routing_context.params.get("id"))
        self.init_components(**properties)

Parsing Params

By default, the params are considered JSON-able. e.g. if the path is "/articles/123" then the 123 is an integer after calling json.loads. If you want to parse the params into a different type, you can use the parse_params method.

class AuthorRoute(Route):
    path = "/authors/:id"
    form = "Pages.Author"

    def parse_params(self, params):
        return {"id": str(params["id"])}

Note

If you have numbers in your params, but these should actually be strings, you can convert these to str in your parse_params method.

You can navigate to a route with params by passing the params option to the navigate function.

from routing.router import navigate

...
    def button_click(self, **event_args):
        navigate(path="/authors/:id", params={"id": 123})

Or equivalently with routing NavLink or Anchor components.

from ._anvil_designer import RowTemplateTemplate
from routing.router import NavLink

class RowTemplate(RowTemplateTemplate):
    def __init__(self, **properties):
        self.init_components(**properties)

        self.add_component(
            NavLink(
                text=f"Author {self.item['name']}",
                path="/authors/:id",
                params={"id": self.item["id"]},
            )
        )

Other equivalent ways to navigate include:

from routing.router import navigate
navigate(path="/authors/123")
# the params will still become {"id": 123}
from routing.router import navigate
from ...routes import AuthorRoute

navigate(path=AuthorRoute.path, params={"id": 123})