rocket_dyn_templates/
metadata.rs

1use std::fmt;
2use std::borrow::Cow;
3
4use rocket::{Request, Rocket, Ignite, Sentinel};
5use rocket::http::{Status, ContentType};
6use rocket::request::{self, FromRequest};
7use rocket::serde::Serialize;
8use rocket::yansi::Paint;
9
10use crate::{Template, context::ContextManager};
11
12/// Request guard for dynamically querying template metadata.
13///
14/// # Usage
15///
16/// The `Metadata` type implements Rocket's [`FromRequest`] trait, so it can be
17/// used as a request guard in any request handler.
18///
19/// ```rust
20/// # #[macro_use] extern crate rocket;
21/// # #[macro_use] extern crate rocket_dyn_templates;
22/// use rocket_dyn_templates::{Template, Metadata, context};
23///
24/// #[get("/")]
25/// fn homepage(metadata: Metadata) -> Template {
26///     // Conditionally render a template if it's available.
27///     # let context = ();
28///     if metadata.contains_template("some-template") {
29///         Template::render("some-template", &context)
30///     } else {
31///         Template::render("fallback", &context)
32///     }
33/// }
34///
35/// fn main() {
36///     rocket::build()
37///         .attach(Template::fairing())
38///         // ...
39///     # ;
40/// }
41/// ```
42pub struct Metadata<'a>(&'a ContextManager);
43
44impl Metadata<'_> {
45    /// Returns `true` if the template with the given `name` is currently
46    /// loaded.  Otherwise, returns `false`.
47    ///
48    /// # Example
49    ///
50    /// ```rust
51    /// # #[macro_use] extern crate rocket;
52    /// # extern crate rocket_dyn_templates;
53    /// #
54    /// use rocket_dyn_templates::Metadata;
55    ///
56    /// #[get("/")]
57    /// fn handler(metadata: Metadata) {
58    ///     // Returns `true` if the template with name `"name"` was loaded.
59    ///     let loaded = metadata.contains_template("name");
60    /// }
61    /// ```
62    pub fn contains_template(&self, name: &str) -> bool {
63        self.0.context().templates.contains_key(name)
64    }
65
66    /// Returns `true` if template reloading is enabled.
67    ///
68    /// # Example
69    ///
70    /// ```rust
71    /// # #[macro_use] extern crate rocket;
72    /// # extern crate rocket_dyn_templates;
73    /// #
74    /// use rocket_dyn_templates::Metadata;
75    ///
76    /// #[get("/")]
77    /// fn handler(metadata: Metadata) {
78    ///     // Returns `true` if template reloading is enabled.
79    ///     let reloading = metadata.reloading();
80    /// }
81    /// ```
82    pub fn reloading(&self) -> bool {
83        self.0.is_reloading()
84    }
85
86    /// Directly render the template named `name` with the context `context`
87    /// into a `String`. Also returns the template's detected `ContentType`. See
88    /// [`Template::render()`] for more details on rendering.
89    ///
90    /// # Examples
91    ///
92    /// ```rust
93    /// # #[macro_use] extern crate rocket;
94    /// use rocket::http::ContentType;
95    /// use rocket_dyn_templates::{Metadata, Template, context};
96    ///
97    /// #[get("/")]
98    /// fn send_email(metadata: Metadata) -> Option<()> {
99    ///     let (mime, string) = metadata.render("email", context! {
100    ///         field: "Hello, world!"
101    ///     })?;
102    ///
103    ///     # /*
104    ///     send_email(mime, string).await?;
105    ///     # */
106    ///     Some(())
107    /// }
108    ///
109    /// #[get("/")]
110    /// fn raw_render(metadata: Metadata) -> Option<(ContentType, String)> {
111    ///     metadata.render("index", context! { field: "Hello, world!" })
112    /// }
113    ///
114    /// // Prefer the following, however, which is nearly identical but pithier:
115    ///
116    /// #[get("/")]
117    /// fn render() -> Template {
118    ///     Template::render("index", context! { field: "Hello, world!" })
119    /// }
120    /// ```
121    pub fn render<S, C>(&self, name: S, context: C) -> Option<(ContentType, String)>
122        where S: Into<Cow<'static, str>>, C: Serialize
123    {
124        Template::render(name.into(), context).finalize(&self.0.context()).ok()
125    }
126}
127
128impl fmt::Debug for Metadata<'_> {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        f.debug_map()
131            .entries(&self.0.context().templates)
132            .finish()
133    }
134}
135
136impl Sentinel for Metadata<'_> {
137    fn abort(rocket: &Rocket<Ignite>) -> bool {
138        if rocket.state::<ContextManager>().is_none() {
139            let md = "Metadata".primary().bold();
140            let fairing = "Template::fairing()".primary().bold();
141            error!("requested `{}` guard without attaching `{}`.", md, fairing);
142            info_!("To use or query templates, you must attach `{}`.", fairing);
143            info_!("See the `Template` documentation for more information.");
144            return true;
145        }
146
147        false
148    }
149}
150
151/// Retrieves the template metadata. If a template fairing hasn't been attached,
152/// an error is printed and an empty `Err` with status `InternalServerError`
153/// (`500`) is returned.
154#[rocket::async_trait]
155impl<'r> FromRequest<'r> for Metadata<'r> {
156    type Error = ();
157
158    async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, ()> {
159        request.rocket().state::<ContextManager>()
160            .map(|cm| request::Outcome::Success(Metadata(cm)))
161            .unwrap_or_else(|| {
162                error_!("Uninitialized template context: missing fairing.");
163                info_!("To use templates, you must attach `Template::fairing()`.");
164                info_!("See the `Template` documentation for more information.");
165                request::Outcome::Error((Status::InternalServerError, ()))
166            })
167    }
168}