credence_lib/render/
default_preparer.rs

1use super::{super::util::*, context::*, preparer::*};
2
3use {axum::http::*, std::result::Result};
4
5/// Default [RenderPreparer].
6///
7/// If the following variables are not already set, will set them:
8///
9/// * `socket`: the [Socket](super::super::middleware::Socket)
10/// * `content`: will render it
11/// * `title`: will extract it from the `content` (the first heading)
12/// * `created`: will use the annotation if set
13/// * `updated`: will use the annotation if set
14/// * `path`: the original URI path
15/// * `query`: the URI query
16pub struct DefaultRenderedPageHandler;
17
18impl RenderPreparer for DefaultRenderedPageHandler {
19    async fn prepare<'own>(&self, context: &mut RenderContext<'own>) -> Result<(), StatusCode> {
20        if let Some(socket) = &context.socket {
21            context.variables.insert("socket".into(), socket.into());
22        }
23
24        context.renderer.clone().prepare(context).await?;
25
26        if !context.variables.contains_key("title") {
27            let title = match &context.rendered_page.content {
28                Some(content) => context.renderer.title_from_content(content)?,
29                None => None,
30            }
31            .unwrap_or("".into());
32
33            context.variables.insert("title".into(), title.into());
34        }
35
36        if !context.variables.contains_key("created") {
37            if let Some(created) = &context.rendered_page.annotations.created {
38                let created = created.inner.timestamp();
39                context.variables.insert("created".into(), created.into());
40            }
41        }
42
43        if !context.variables.contains_key("updated") {
44            if let Some(updated) = &context.rendered_page.annotations.updated {
45                let updated = updated.inner.timestamp();
46                context.variables.insert("updated".into(), updated.into());
47            }
48        }
49
50        if !context.variables.contains_key("path") {
51            let original_path = context.original_uri_path.clone().unwrap_or_default();
52            context.variables.insert("path".into(), original_path.into());
53        }
54
55        if !context.variables.contains_key("query") {
56            if let Some(query) = &context.query {
57                context.variables.insert("query".into(), query_map_to_variant(query));
58            }
59        }
60
61        Ok(())
62    }
63}