Skip to main content

rocket_include_handlebars/debug/
manager.rs

1use std::sync::{Mutex, PoisonError};
2
3use serde::Serialize;
4
5use super::{HandlebarsResponse, ReloadableHandlebars};
6use crate::{EtagIfNoneMatch, functions::compute_data_etag};
7
8/// To monitor the state of Handlebars.
9#[derive(Educe)]
10#[educe(Debug)]
11pub struct HandlebarsContextManager {
12    pub handlebars: Mutex<ReloadableHandlebars>,
13}
14
15impl HandlebarsContextManager {
16    #[inline]
17    pub(crate) fn new(
18        handlebars: Mutex<ReloadableHandlebars>,
19        _cache_capacity: usize,
20    ) -> HandlebarsContextManager {
21        HandlebarsContextManager {
22            handlebars,
23        }
24    }
25
26    /// Build a `HandlebarsResponse`.
27    #[inline]
28    pub fn build<S: AsRef<str>, V: Serialize>(
29        &self,
30        etag_if_none_match: &EtagIfNoneMatch<'_>,
31        minify: bool,
32        name: S,
33        context: V,
34    ) -> HandlebarsResponse {
35        let html = self.render(name, context);
36        let etag = compute_data_etag(html.as_bytes());
37
38        if etag_if_none_match.weak_eq(&etag) {
39            return HandlebarsResponse::not_modified_with_etag(&etag);
40        }
41
42        let html = if minify { html_minifier::minify(&html).unwrap_or(html) } else { html };
43
44        HandlebarsResponse::build_not_cache(html, etag)
45    }
46
47    /// Render a template.
48    #[inline]
49    pub fn render<S: AsRef<str>, V: Serialize>(&self, name: S, context: V) -> String {
50        self.handlebars
51            .lock()
52            .unwrap_or_else(PoisonError::into_inner)
53            .render(name.as_ref(), &context)
54            .unwrap()
55    }
56}