query_segments.rs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //! Example: Url query segments usage
  2. //! ------------------------------------
  3. //!
  4. //! This example shows how to access and use multiple query segments present in an url on the web.
  5. //!
  6. //! Run `dx serve` and navigate to `http://localhost:8080/blog?name=John&surname=Doe`
  7. use dioxus::prelude::*;
  8. use std::fmt::Display;
  9. #[derive(Routable, Clone)]
  10. #[rustfmt::skip]
  11. enum Route {
  12. // segments that start with ?:.. are query segments that capture the entire query
  13. #[route("/blog?:..query_params")]
  14. BlogPost {
  15. // You must include query segments in child variants
  16. query_params: ManualBlogQuerySegments,
  17. },
  18. // segments that follow the ?:field&:other_field syntax are query segments that follow the standard url query syntax
  19. #[route("/autoblog?:name&:surname")]
  20. AutomaticBlogPost {
  21. name: String,
  22. surname: String,
  23. },
  24. }
  25. #[derive(Debug, Clone, PartialEq)]
  26. struct ManualBlogQuerySegments {
  27. name: String,
  28. surname: String,
  29. }
  30. /// The display impl needs to display the query in a way that can be parsed:
  31. impl Display for ManualBlogQuerySegments {
  32. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  33. write!(f, "name={}&surname={}", self.name, self.surname)
  34. }
  35. }
  36. /// 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.
  37. impl FromQuery for ManualBlogQuerySegments {
  38. fn from_query(query: &str) -> Self {
  39. let mut name = None;
  40. let mut surname = None;
  41. let pairs = form_urlencoded::parse(query.as_bytes());
  42. pairs.for_each(|(key, value)| {
  43. if key == "name" {
  44. name = Some(value.clone().into());
  45. }
  46. if key == "surname" {
  47. surname = Some(value.clone().into());
  48. }
  49. });
  50. Self {
  51. name: name.unwrap(),
  52. surname: surname.unwrap(),
  53. }
  54. }
  55. }
  56. #[component]
  57. fn BlogPost(query_params: ManualBlogQuerySegments) -> Element {
  58. rsx! {
  59. div { "This is your blogpost with a query segment:" }
  60. div { "{query_params:?}" }
  61. }
  62. }
  63. #[component]
  64. fn AutomaticBlogPost(name: String, surname: String) -> Element {
  65. rsx! {
  66. div { "This is your blogpost with a query segment:" }
  67. div { "name={name}&surname={surname}" }
  68. }
  69. }
  70. #[component]
  71. fn App() -> Element {
  72. rsx! { Router::<Route> {} }
  73. }
  74. fn main() {
  75. launch(App);
  76. }