main.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #![allow(non_snake_case, unused)]
  2. //! Example: Url query segments usage
  3. //! ------------------------------------
  4. //!
  5. //! This example shows how to access and use multiple query segments present in an url on the web.
  6. //!
  7. //! Run `dx serve` and navigate to `http://localhost:8080/blog?name=John&surname=Doe`
  8. use std::fmt::Display;
  9. use dioxus::prelude::*;
  10. use dioxus_router::prelude::*;
  11. // ANCHOR: route
  12. #[derive(Routable, Clone)]
  13. #[rustfmt::skip]
  14. enum Route {
  15. // segments that start with ?: are query segments
  16. #[route("/blog?:query_params")]
  17. BlogPost {
  18. // You must include query segments in child variants
  19. query_params: BlogQuerySegments,
  20. },
  21. }
  22. #[derive(Debug, Clone, PartialEq)]
  23. struct BlogQuerySegments {
  24. name: String,
  25. surname: String,
  26. }
  27. /// The display impl needs to display the query in a way that can be parsed:
  28. impl Display for BlogQuerySegments {
  29. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  30. write!(f, "name={}&surname={}", self.name, self.surname)
  31. }
  32. }
  33. /// The query segment is anything that implements https://docs.rs/dioxus-router/latest/dioxus_router/routable/trait.FromQuery.html. You can implement that trait for a struct if you want to parse multiple query parameters.
  34. impl FromQuery for BlogQuerySegments {
  35. fn from_query(query: &str) -> Self {
  36. let mut name = None;
  37. let mut surname = None;
  38. let pairs = form_urlencoded::parse(query.as_bytes());
  39. pairs.for_each(|(key, value)| {
  40. if key == "name" {
  41. name = Some(value.clone().into());
  42. }
  43. if key == "surname" {
  44. surname = Some(value.clone().into());
  45. }
  46. });
  47. Self {
  48. name: name.unwrap(),
  49. surname: surname.unwrap(),
  50. }
  51. }
  52. }
  53. #[inline_props]
  54. fn BlogPost(cx: Scope, query_params: BlogQuerySegments) -> Element {
  55. render! {
  56. div{"This is your blogpost with a query segment:"}
  57. div{format!("{:?}", query_params)}
  58. }
  59. }
  60. fn App(cx: Scope) -> Element {
  61. render! { Router::<Route>{} }
  62. }
  63. fn main() {
  64. dioxus_web::launch(App);
  65. }