Skip to main content

livewire/
page.rs

1//! Page components: a component whose view renders the whole document.
2//!
3//! An embedded component is mounted from a page template with `{{ livewire(..) }}`. A page
4//! component has no page template: its own `.livewire` view extends the application layout, and the
5//! route answers with the component's rendered markup.
6//!
7//! ```text
8//! {# resources/views/livewire/post-browser.livewire #}
9//! {% extends "layouts.app" %}
10//! {% block content %}<h1>Posts</h1>{% endblock %}
11//! ```
12//!
13//! The route then mounts it exactly as a page would:
14//!
15//! ```no_run
16//! # use std::sync::Arc;
17//! # use livewire::ComponentRegistry;
18//! # use livewire::component::Params;
19//! # fn run(registry: Arc<ComponentRegistry>) -> livewire::Result<()> {
20//! let html = livewire::page::render_page(&registry, "post-browser", Params::default())?;
21//! # let _ = html;
22//! # Ok(())
23//! # }
24//! ```
25//!
26//! # What a component gains, and does not
27//!
28//! The mount lifecycle, props, and the update endpoint are the same as an embedded component's; only
29//! the surrounding document comes from the component. Route parameters and persistent middleware
30//! belong to the application's routing layer, which passes them as props.
31
32use std::sync::Arc;
33
34use serde_json::Map;
35
36use crate::component::Params;
37use crate::error::LivewireError;
38use crate::registry::ComponentRegistry;
39
40/// Mounts `name` as a page and returns the markup the route answers with.
41///
42/// # Errors
43///
44/// Fails when the component is not registered, when its mount fails, or when its view renders no
45/// single root element — the same failures an embedded mount reports.
46pub fn render_page(registry: &Arc<ComponentRegistry>, name: &str, params: Params) -> Result<String, LivewireError> {
47    let rendered = crate::render::mount(registry, name, params, None, Map::new())?;
48
49    Ok(rendered.html)
50}
51
52#[cfg(test)]
53mod tests {
54    use super::render_page;
55    use crate::component::Params;
56    use crate::error::LivewireError;
57    use crate::registry::ComponentRegistry;
58    use std::sync::Arc;
59
60    #[test]
61    fn an_unregistered_page_names_the_component_it_could_not_find() {
62        let registry = Arc::new(ComponentRegistry::new(Default::default()));
63
64        let error = render_page(&registry, "missing", Params::default()).expect_err("no such component");
65
66        assert!(
67            matches!(error, LivewireError::ComponentNotFound { ref name } if name == "missing"),
68            "{error}"
69        );
70    }
71}