static_generation.rs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #![allow(non_snake_case)]
  2. use dioxus::prelude::*;
  3. use dioxus_router::prelude::*;
  4. use std::io::prelude::*;
  5. use std::{path::PathBuf, str::FromStr};
  6. fn main() {
  7. render_static_pages();
  8. }
  9. fn render_static_pages() {
  10. for route in Route::SITE_MAP
  11. .iter()
  12. .flat_map(|seg| seg.flatten().into_iter())
  13. {
  14. // check if this is a static segment
  15. let mut file_path = PathBuf::from("./");
  16. let mut full_path = String::new();
  17. let mut is_static = true;
  18. for segment in &route {
  19. match segment {
  20. SegmentType::Static(s) => {
  21. file_path.push(s);
  22. full_path += "/";
  23. full_path += s;
  24. }
  25. _ => {
  26. // skip routes with any dynamic segments
  27. is_static = false;
  28. break;
  29. }
  30. }
  31. }
  32. if is_static {
  33. let route = Route::from_str(&full_path).unwrap();
  34. let mut vdom = VirtualDom::new_with_props(RenderPath, RenderPathProps { path: route });
  35. let _ = vdom.rebuild();
  36. file_path.push("index.html");
  37. std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
  38. let mut file = std::fs::File::create(file_path).unwrap();
  39. let body = dioxus_ssr::render(&vdom);
  40. let html = format!(
  41. r#"
  42. <!DOCTYPE html>
  43. <html lang="en">
  44. <head>
  45. <meta charset="UTF-8">
  46. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  47. <title>{}</title>
  48. </head>
  49. <body>
  50. {}
  51. </body>
  52. </html>
  53. "#,
  54. full_path, body
  55. );
  56. file.write_all(html.as_bytes()).unwrap();
  57. }
  58. }
  59. }
  60. #[inline_props]
  61. fn RenderPath(cx: Scope, path: Route) -> Element {
  62. let path = path.clone();
  63. render! {
  64. Router {
  65. config: || RouterConfig::default().history(MemoryHistory::with_initial_path(path))
  66. }
  67. }
  68. }
  69. #[inline_props]
  70. fn Blog(cx: Scope) -> Element {
  71. render! {
  72. div {
  73. "Blog"
  74. }
  75. }
  76. }
  77. #[inline_props]
  78. fn Post(cx: Scope) -> Element {
  79. render! {
  80. div {
  81. "Post"
  82. }
  83. }
  84. }
  85. #[inline_props]
  86. fn Home(cx: Scope) -> Element {
  87. render! {
  88. div {
  89. "Home"
  90. }
  91. }
  92. }
  93. #[rustfmt::skip]
  94. #[derive(Clone, Debug, PartialEq, Routable)]
  95. enum Route {
  96. #[nest("/blog")]
  97. #[route("/")]
  98. Blog {},
  99. #[route("/post")]
  100. Post {},
  101. #[end_nest]
  102. #[route("/")]
  103. Home {},
  104. }