Skip to content

Instantly share code, notes, and snippets.

@BlackAsLight
Last active July 27, 2023 10:56
Show Gist options
  • Save BlackAsLight/0476e897d5929a79ed7c9dff21dc606f to your computer and use it in GitHub Desktop.
Save BlackAsLight/0476e897d5929a79ed7c9dff21dc606f to your computer and use it in GitHub Desktop.
Creating the static .html files of a leptos project
[dependencies]
leptos = { git = "https://github.com/leptos-rs/leptos", branch = "main", default-features = false, features = [
"serde",
"nightly",
] }
leptos_meta = { git = "https://github.com/leptos-rs/leptos", branch = "main", default-features = false, features = [
"nightly",
] }
leptos_router = { git = "https://github.com/leptos-rs/leptos", branch = "main", default-features = false, features = [
"nightly",
] }
[features]
default = ["static"]
static = ["leptos/ssr"]
#[cfg(feature = "static")]
fn main() {
use std::{
fs::{self, File},
io::Write,
path::Path,
};
use leptos::*;
use crate::app::App;
fs::create_dir_all("./static/html").unwrap();
let routes = leptos_router::generate_route_list_inner(|cx: Scope| view! { cx, <App/> });
for route in routes {
let path = format!("./static/html{}.html", if route.path().len() == 0 { "/index" } else { route.path() });
let path = Path::new(&path);
if path.exists() {
fs::remove_file(path).unwrap();
}
let mut file = File::create(path).unwrap();
file.write_all(ssr::render_to_string(move |cx| view! {cx, <App path={route.path().into()}/> }).as_bytes())
.unwrap();
}
}
use leptos::*;
use leptos_meta::Title;
use leptos_router::{Route, Router, Routes, A};
#[component]
pub fn App(cx: Scope, #[prop(optional)] path: Option<String>) -> impl IntoView {
if let Some(path) = path {
provide_context(
cx,
RouterIntegrationContext::new(ServerIntegration {
path: format!("http://localhost{path}"),
}),
)
}
view! { cx,
<Router>
<A href="/">"Main"</A>
<A href="/about">"About"</A>
<Routes>
<Route path="/" view=|cx| view! { cx,
<Title text="Home" />
<h1>"Main Page"</h1>
}
/>
<Route path="/about" view=|cx| view! { cx,
<Title text="About" />
<h1>"About Page"</h1>
}
/>
</Routes>
</Router>
}
}
// If you have any server fns, to remove the need to have their dependencies attached to the static run,
// you can create a blank server fn like this to mask the real one when static feature is enabled.
// You'd need to do this for every server function.
#[server(Logout, "/", "GetJson", "logout")]
#[cfg(feature = "static")]
async fn get(_cx: Scope) -> Result<(), ServerFnError> {
Ok(())
}
#[cfg(not(feature = "static"))]
#[server(Logout, "/", "GetJson", "logout")]
async fn get(cx: Scope) -> Result<(), ServerFnError> {
use actix_identity::Identity;
if let Some(identity) = leptos_actix::extract(cx, |identity: Option<Identity>| async { identity }).await? {
identity.logout();
}
leptos_actix::redirect(cx, "/");
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment