dioxus/packages/ssr/src/lib.rs

56 lines
1.7 KiB
Rust
Raw Normal View History

#![doc = include_str!("../README.md")]
2021-01-21 07:25:44 +00:00
2022-11-16 00:05:22 +00:00
mod cache;
pub mod config;
pub mod renderer;
2022-11-03 00:29:18 +00:00
pub mod template;
2022-12-07 01:41:47 +00:00
use dioxus_core::{Element, LazyNodes, Scope, VirtualDom};
use std::cell::Cell;
2022-12-07 01:50:25 +00:00
pub use crate::renderer::Renderer;
2022-12-07 01:41:47 +00:00
/// A convenience function to render an `rsx!` call to a string
///
/// For advanced rendering, create a new `SsrRender`.
2022-12-07 01:44:29 +00:00
pub fn render_lazy(f: LazyNodes<'_, '_>) -> String {
2022-12-07 01:41:47 +00:00
// We need to somehow get the lazy call into the virtualdom even with the lifetime
// Since the lazy lifetime is valid for this function, we can just transmute it to static temporarily
// This is okay since we're returning an owned value
struct RootProps<'a, 'b> {
caller: Cell<Option<LazyNodes<'a, 'b>>>,
}
fn lazy_app<'a>(cx: Scope<'a, RootProps<'static, 'static>>) -> Element<'a> {
let lazy = cx.props.caller.take().unwrap();
let lazy: LazyNodes = unsafe { std::mem::transmute(lazy) };
Some(lazy.call(cx))
2022-12-07 01:41:47 +00:00
}
let props: RootProps = unsafe {
std::mem::transmute(RootProps {
caller: Cell::new(Some(f)),
})
};
let mut dom = VirtualDom::new_with_props(lazy_app, props);
_ = dom.rebuild();
Renderer::new().render(&dom)
}
/// A convenience function to render an existing VirtualDom to a string
///
/// We generally recommend creating a new `Renderer` to take advantage of template caching.
pub fn render(dom: &VirtualDom) -> String {
Renderer::new().render(dom)
}
2022-12-07 01:50:25 +00:00
/// A convenience function to pre-render an existing VirtualDom to a string
///
/// We generally recommend creating a new `Renderer` to take advantage of template caching.
pub fn pre_render(dom: &VirtualDom) -> String {
let mut renderer = Renderer::new();
renderer.pre_render = true;
renderer.render(dom)
}