Support named wildcards when deriving Routable. (#2345)

This commit is contained in:
Jonathan Bailey 2022-01-12 05:27:14 -08:00 committed by GitHub
parent b165037381
commit 923f6434df
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 25 additions and 5 deletions

View File

@ -172,8 +172,10 @@ impl Routable {
for field in fields.iter() {
// :param -> {param}
// *param -> {param}
// so we can pass it to `format!("...", param)`
right = right.replace(&format!(":{}", field), &format!("{{{}}}", field))
right = right.replace(&format!(":{}", field), &format!("{{{}}}", field));
right = right.replace(&format!("*{}", field), &format!("{{{}}}", field));
}
quote! {

View File

@ -6,11 +6,19 @@ enum Routes {
One,
#[at("/two/:id")]
Two { id: u32 },
#[at("/:a/:b")]
Three { a: u32, b: u32 },
#[at("/:a/:b/*rest")]
Three { a: u32, b: u32, rest: ::std::string::String },
#[at("/404")]
#[not_found]
NotFound,
}
#[derive(Debug, PartialEq, Clone, ::yew_router::Routable)]
enum MoreRoutes {
#[at("/subpath/*rest")]
Subpath { rest: ::std::string::String },
#[at("/*all")]
CatchAll { all: ::std::string::String },
}
fn main() {}

View File

@ -47,6 +47,8 @@ where
{
/// Callback which returns [`Html`] to be rendered for the current route.
pub render: RenderFn<R>,
#[prop_or_default]
pub pathname: Option<String>,
}
#[doc(hidden)]
@ -93,7 +95,12 @@ where
}
fn view(&self, ctx: &Context<Self>) -> Html {
let route = ctx.link().route::<R>();
let route = ctx
.props()
.pathname
.as_ref()
.and_then(|p| R::recognize(p))
.or_else(|| ctx.link().route::<R>());
let children = match &route {
Some(ref route) => (ctx.props().render.0)(route),

View File

@ -102,7 +102,7 @@ fn app() -> Html {
### Path Segments
It is also possible to extract information from a route.
It is also possible to extract information from a route using dynamic and named wildcard segments.
You can then access the post's id inside `<Switch />` and forward it to the appropriate component via properties.
```rust
@ -115,12 +115,15 @@ enum Route {
Home,
#[at("/post/:id")]
Post { id: String },
#[at("/*path")]
Misc { path: String },
}
fn switch(route: &Route) -> Html {
match route {
Route::Home => html! { <h1>{ "Home" }</h1> },
Route::Post { id } => html! {<p>{format!("You are looking at Post {}", id)}</p>},
Route::Misc { path } => html! {<p>{format!("Matched some other path: {}", path)}</p>},
}
}
```