pub trait ToRouteSegments {
// Required method
fn display_route_segments(&self, f: &mut Formatter<'_>) -> Result;
}
Expand description
Something that can be converted into multiple route segments. This must be implemented for any type that is spread into the route segment like #[route("/:..route_segments")]
.
This trait is automatically implemented for any types that implement IntoIterator<Item=impl Display>
.
use dioxus::prelude::*;
#[derive(Routable, Clone, PartialEq, Debug)]
enum Route {
// FromRouteSegments must be implemented for any types you use in the route segment
// When you spread the route, you can parse multiple values from the route
// This url will be in the format `/123/456/789`
#[route("/:..numeric_route_segments")]
Home {
numeric_route_segments: NumericRouteSegments,
},
}
// We can derive Default for NumericRouteSegments
// If the router fails to parse the route segment, it will use the default value instead
#[derive(Default, PartialEq, Clone, Debug)]
struct NumericRouteSegments {
numbers: Vec<i32>,
}
// Implement ToRouteSegments for NumericRouteSegments so that we can display the route segments
impl ToRouteSegments for NumericRouteSegments {
fn display_route_segments(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for number in &self.numbers {
write!(f, "/{}", number)?;
}
Ok(())
}
}
// We also need to parse the route segments with `FromRouteSegments`
impl FromRouteSegments for NumericRouteSegments {
type Err = <i32 as std::str::FromStr>::Err;
fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err> {
let mut numbers = Vec::new();
for segment in segments {
numbers.push(segment.parse()?);
}
Ok(NumericRouteSegments { numbers })
}
}
Required Methods§
Sourcefn display_route_segments(&self, f: &mut Formatter<'_>) -> Result
fn display_route_segments(&self, f: &mut Formatter<'_>) -> Result
Display the route segments with each route segment separated by a /
. This should not start with a /
.