Skip to main content

rocket_dyn_templates/
template.rs

1use std::borrow::Cow;
2use std::path::PathBuf;
3
4use rocket::{Rocket, Orbit, Ignite, Sentinel};
5use rocket::request::Request;
6use rocket::response::{self, Responder};
7use rocket::http::{ContentType, Status};
8use rocket::figment::{value::Value, error::Error};
9use rocket::serde::Serialize;
10use rocket::yansi::Paint;
11
12use crate::context::{Context, ContextManager};
13
14pub(crate) const DEFAULT_TEMPLATE_DIR: &str = "templates";
15
16/// Responder that renders a dynamic template.
17///
18/// `Template` serves as a _proxy_ type for rendering a template and _does not_
19/// contain the rendered template itself. The template is lazily rendered, at
20/// response time. To render a template greedily, use [`Template::show()`].
21///
22/// See the [crate root](crate) for usage details.
23#[derive(Debug)]
24pub struct Template {
25    name: Cow<'static, str>,
26    value: Result<Value, Error>,
27}
28
29#[derive(Debug)]
30pub(crate) struct TemplateInfo {
31    /// The complete path, including `template_dir`, to this template, if any.
32    pub(crate) path: Option<PathBuf>,
33    /// The extension for the engine of this template.
34    pub(crate) engine_ext: &'static str,
35    /// The extension before the engine extension in the template, if any.
36    pub(crate) data_type: ContentType
37}
38
39impl Template {
40    /// Render the template named `name` with the context `context`. The
41    /// `context` is typically created using the [`context!`](crate::context!)
42    /// macro, but it can be of any type that implements `Serialize`, such as
43    /// `HashMap` or a custom `struct`.
44    ///
45    /// To render a template directly into a string, use
46    /// [`Metadata::render()`](crate::Metadata::render()).
47    ///
48    /// # Examples
49    ///
50    /// Using the `context` macro:
51    ///
52    /// ```rust
53    /// use rocket_dyn_templates::{Template, context};
54    ///
55    /// let template = Template::render("index.html", context! {
56    ///     foo: "Hello, world!",
57    /// });
58    /// ```
59    ///
60    /// Using a `HashMap` as the context:
61    ///
62    /// ```rust
63    /// use std::collections::HashMap;
64    /// use rocket_dyn_templates::Template;
65    ///
66    /// // Create a `context` from a `HashMap`.
67    /// let mut context = HashMap::new();
68    /// context.insert("foo", "Hello, world!");
69    ///
70    /// let template = Template::render("index.html", context);
71    /// ```
72    #[inline]
73    pub fn render<S, C>(name: S, context: C) -> Template
74        where S: Into<Cow<'static, str>>, C: Serialize
75    {
76        Template {
77            name: name.into(),
78            value: Value::serialize(context),
79        }
80    }
81
82    /// Render the template named `name` with the context `context` into a
83    /// `String`. This method should **not** be used in any running Rocket
84    /// application. This method should only be used during testing to validate
85    /// `Template` responses. For other uses, use [`render()`](#method.render)
86    /// instead.
87    ///
88    /// The `context` can be of any type that implements `Serialize`. This is
89    /// typically a `HashMap` or a custom `struct`.
90    ///
91    /// Returns `Some` if the template could be rendered. Otherwise, returns
92    /// `None`. If rendering fails, error output is printed to the console.
93    /// `None` is also returned if a `Templating` fairing has not been attached.
94    ///
95    /// # Example
96    ///
97    /// ```rust,no_run
98    /// # extern crate rocket;
99    /// # extern crate rocket_dyn_templates;
100    /// use std::collections::HashMap;
101    ///
102    /// use rocket_dyn_templates::{Template, Templating};
103    /// use rocket::local::blocking::Client;
104    ///
105    /// fn main() {
106    ///     let rocket = rocket::build().attach(Templating::new());
107    ///     let client = Client::untracked(rocket).expect("valid rocket");
108    ///
109    ///     // Create a `context`. Here, just an empty `HashMap`.
110    ///     let mut context = HashMap::new();
111    ///     # context.insert("test", "test");
112    ///     let template =
113    ///         Template::show(client.rocket(), "index.html", context);
114    /// }
115    /// ```
116    #[inline]
117    pub fn show<S, C>(rocket: &Rocket<Orbit>, name: S, context: C) -> Option<String>
118        where S: Into<Cow<'static, str>>, C: Serialize
119    {
120        let ctxt = rocket.state::<ContextManager>().map(ContextManager::context).or_else(|| {
121            warn!("Uninitialized template context: missing fairing.");
122            info!("To use templates, you must attach `Templating::new()`.");
123            info!("See the `Templating` documentation for more information.");
124            None
125        })?;
126
127        Template::render(name, context).finalize(&ctxt).ok().map(|v| v.1)
128    }
129
130    /// Actually render this template given a template context. This method is
131    /// called by the `Template` `Responder` implementation as well as
132    /// `Template::show()`.
133    #[inline(always)]
134    pub(crate) fn finalize(self, ctxt: &Context) -> Result<(ContentType, String), Status> {
135        let name = &*self.name;
136        let info = ctxt.templates.get(name).ok_or_else(|| {
137            let ts: Vec<_> = ctxt.templates.keys().map(|s| s.as_str()).collect();
138            error_!("Template '{}' does not exist.", name);
139            for known in ts.iter().filter(|t| is_name_without_extension(name, t)) {
140                info_!("Did you mean '{}'? Names include the file type extension.", known);
141            }
142
143            info_!("Known templates: {}.", ts.join(", "));
144            info_!("Searched in {:?}.", ctxt.root);
145            Status::InternalServerError
146        })?;
147
148        let value = self.value.map_err(|e| {
149            error_!("Template context failed to serialize: {}.", e);
150            Status::InternalServerError
151        })?;
152
153        let string = ctxt.engines.render(name, info, value).ok_or_else(|| {
154            error_!("Template '{}' failed to render.", name);
155            Status::InternalServerError
156        })?;
157
158        Ok((info.data_type.clone(), string))
159    }
160}
161
162/// Returns `true` if `known` is `name` followed by a file type extension, as
163/// in `index` and `index.html`.
164fn is_name_without_extension(name: &str, known: &str) -> bool {
165    known.strip_prefix(name)
166        .and_then(|rest| rest.strip_prefix('.'))
167        .is_some_and(|ext| !ext.is_empty() && !ext.contains(['.', '/']))
168}
169
170/// Returns a response with the Content-Type derived from the template's
171/// extension and a fixed-size body containing the rendered template. If
172/// rendering fails, an `Err` of `Status::InternalServerError` is returned.
173impl<'r> Responder<'r, 'static> for Template {
174    fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
175        let ctxt = req.rocket()
176            .state::<ContextManager>()
177            .ok_or_else(|| {
178                error_!("Uninitialized template context: missing fairing.");
179                info_!("To use templates, you must attach `Templating::new()`.");
180                info_!("See the `Templating` documentation for more information.");
181                Status::InternalServerError
182            })?;
183
184        self.finalize(&ctxt.context())?.respond_to(req)
185    }
186}
187
188impl Sentinel for Template {
189    fn abort(rocket: &Rocket<Ignite>) -> bool {
190        if rocket.state::<ContextManager>().is_none() {
191            let template = "Template".primary().bold();
192            let fairing = "Templating::new()".primary().bold();
193            error!("returning `{}` responder without attaching `{}`.", template, fairing);
194            info_!("To use or query templates, you must attach `{}`.", fairing);
195            info_!("See the `Templating` documentation for more information.");
196            return true;
197        }
198
199        false
200    }
201}
202
203/// A macro to easily create a template rendering context.
204///
205/// Invocations of this macro expand to a value of an anonymous type which
206/// implements [`serde::Serialize`](rocket::serde::Serialize). Fields can be
207/// literal expressions or variables captured from a surrounding scope, as long
208/// as all fields implement `Serialize`.
209///
210/// # Examples
211///
212/// The following code:
213///
214/// ```rust
215/// # #[macro_use] extern crate rocket;
216/// # use rocket_dyn_templates::{Template, context};
217/// #[get("/<foo>")]
218/// fn render_index(foo: u64) -> Template {
219///     Template::render("index.html", context! {
220///         // Note that shorthand field syntax is supported.
221///         // This is equivalent to `foo: foo,`
222///         foo,
223///         bar: "Hello world",
224///     })
225/// }
226/// ```
227///
228/// is equivalent to the following, but without the need to manually define an
229/// `IndexContext` struct:
230///
231/// ```rust
232/// # use rocket_dyn_templates::Template;
233/// # use rocket::serde::Serialize;
234/// # use rocket::get;
235/// #[derive(Serialize)]
236/// # #[serde(crate = "rocket::serde")]
237/// struct IndexContext<'a> {
238///     foo: u64,
239///     bar: &'a str,
240/// }
241///
242/// #[get("/<foo>")]
243/// fn render_index(foo: u64) -> Template {
244///     Template::render("index.html", IndexContext {
245///         foo,
246///         bar: "Hello world",
247///     })
248/// }
249/// ```
250///
251/// ## Nesting
252///
253/// Nested objects can be created by nesting calls to `context!`:
254///
255/// ```rust
256/// # use rocket_dyn_templates::context;
257/// # fn main() {
258/// let ctx = context! {
259///     planet: "Earth",
260///     info: context! {
261///         mass: 5.97e24,
262///         radius: "6371 km",
263///         moons: 1,
264///     },
265/// };
266/// # }
267/// ```
268#[macro_export]
269macro_rules! context {
270    ($($key:ident $(: $value:expr)?),*$(,)?) => {{
271        use $crate::serde::ser::{Serialize, Serializer, SerializeMap};
272        use ::std::fmt::{Debug, Formatter};
273        use ::std::result::Result;
274
275        #[allow(non_camel_case_types)]
276        struct ContextMacroCtxObject<$($key: Serialize),*> {
277            $($key: $key),*
278        }
279
280        #[allow(non_camel_case_types)]
281        impl<$($key: Serialize),*> Serialize for ContextMacroCtxObject<$($key),*> {
282            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
283                where S: Serializer,
284            {
285                let mut map = serializer.serialize_map(None)?;
286                $(map.serialize_entry(stringify!($key), &self.$key)?;)*
287                map.end()
288            }
289        }
290
291        #[allow(non_camel_case_types)]
292        impl<$($key: Debug + Serialize),*> Debug for ContextMacroCtxObject<$($key),*> {
293            fn fmt(&self, f: &mut Formatter<'_>) -> ::std::fmt::Result {
294                f.debug_struct("context!")
295                    $(.field(stringify!($key), &self.$key))*
296                    .finish()
297            }
298        }
299
300        ContextMacroCtxObject {
301            $($key $(: $value)?),*
302        }
303    }};
304}
305
306#[cfg(test)]
307mod tests {
308    use super::is_name_without_extension;
309
310    #[test]
311    fn name_without_extension() {
312        assert!(is_name_without_extension("index", "index.html"));
313        assert!(is_name_without_extension("dir/index", "dir/index.html"));
314        assert!(is_name_without_extension("index.template", "index.template.html"));
315
316        assert!(!is_name_without_extension("index", "index"));
317        assert!(!is_name_without_extension("index", "index."));
318        assert!(!is_name_without_extension("index", "indexes.html"));
319        assert!(!is_name_without_extension("index", "index.template.html"));
320        assert!(!is_name_without_extension("index", "index.d/page"));
321        assert!(!is_name_without_extension("index.html", "index"));
322    }
323}