ToQueryArgument

Trait ToQueryArgument 

Source
pub trait ToQueryArgument<T = ()> {
    // Required method
    fn display_query_argument(
        &self,
        query_name: &str,
        f: &mut Formatter<'_>,
    ) -> Result;
}
Expand description

Something that can be formatted as a query argument. This trait must be implemented for any type that is used as a query argument like #[route("/?:query")].

This trait is automatically implemented for any types that implement Display.

use dioxus::prelude::*;

#[derive(Routable, Clone, PartialEq, Debug)]
enum Route {
    // FromQuerySegment must be implemented for any types you use in the query segment
    // When you don't spread the query, you can parse multiple values form the query
    // This url will be in the format `/?query=123&other=456`
    #[route("/?:query&:other")]
    Home {
        query: CustomQuery,
        other: i32,
    },
}

// We can derive Default for CustomQuery
// If the router fails to parse the query value, it will use the default value instead
#[derive(Default, Clone, PartialEq, Debug)]
struct CustomQuery {
    count: i32,
}

// We implement FromStr for CustomQuery so that FromQuerySegment is implemented automatically
impl std::str::FromStr for CustomQuery {
    type Err = <i32 as std::str::FromStr>::Err;

    fn from_str(query: &str) -> Result<Self, Self::Err> {
        Ok(CustomQuery {
            count: query.parse()?,
        })
    }
}

// We also need to implement Display for CustomQuery so that ToQueryArgument is implemented automatically
impl std::fmt::Display for CustomQuery {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.count)
    }
}

Required Methods§

Source

fn display_query_argument( &self, query_name: &str, f: &mut Formatter<'_>, ) -> Result

Display the query argument as a string.

Implementations on Foreign Types§

Source§

impl<T: Display> ToQueryArgument<OptionMarker> for Option<T>

Source§

fn display_query_argument( &self, query_name: &str, f: &mut Formatter<'_>, ) -> Result

Implementors§

Source§

impl<T> ToQueryArgument for T
where T: Display,