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::trace::Trace;
10use rocket::serde::Serialize;
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>()
121 .map(ContextManager::context)
122 .or_else(|| {
123 error!("Uninitialized template context: missing fairing.\n\
124 To use templates, you must attach `Templating::new()`.\n\
125 See the `Templating` documentation for more information.");
126
127 None
128 })?;
129
130 Template::render(name, context).finalize(&ctxt).ok().map(|v| v.1)
131 }
132
133 /// Actually render this template given a template context. This method is
134 /// called by the `Template` `Responder` implementation as well as
135 /// `Template::show()`.
136 #[inline(always)]
137 pub(crate) fn finalize(self, ctxt: &Context) -> Result<(ContentType, String), Status> {
138 let template = &*self.name;
139 let info = ctxt.templates.get(template).ok_or_else(|| {
140 let ts: Vec<_> = ctxt.templates.keys().map(|s| s.as_str()).collect();
141 error!(
142 %template, search_path = %ctxt.root.display(), known_templates = ?ts,
143 "requested template not found"
144 );
145
146 for known in ts.iter().filter(|t| is_name_without_extension(template, t)) {
147 info!("Did you mean '{known}'? Names include the file type extension.");
148 }
149
150 Status::InternalServerError
151 })?;
152
153 let value = self.value.map_err(|e| {
154 span_error!("templating", "template context failed to serialize" => e.trace_error());
155 Status::InternalServerError
156 })?;
157
158 let string = ctxt.engines.render(template, info, value).ok_or_else(|| {
159 error!(template, "template failed to render");
160 Status::InternalServerError
161 })?;
162
163 Ok((info.data_type.clone(), string))
164 }
165}
166
167/// Returns `true` if `known` is `name` followed by a file type extension, as
168/// in `index` and `index.html`.
169fn is_name_without_extension(name: &str, known: &str) -> bool {
170 known.strip_prefix(name)
171 .and_then(|rest| rest.strip_prefix('.'))
172 .is_some_and(|ext| !ext.is_empty() && !ext.contains(['.', '/']))
173}
174
175/// Returns a response with the Content-Type derived from the template's
176/// extension and a fixed-size body containing the rendered template. If
177/// rendering fails, an `Err` of `Status::InternalServerError` is returned.
178impl<'r> Responder<'r, 'static> for Template {
179 fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
180 let ctxt = req.rocket()
181 .state::<ContextManager>()
182 .ok_or_else(|| {
183 error!(
184 "Uninitialized template context: missing fairing.\n\
185 To use templates, you must attach `Templating::new()`.\n\
186 See the `Templating` documentation for more information."
187 );
188
189 Status::InternalServerError
190 })?;
191
192 self.finalize(&ctxt.context())?.respond_to(req)
193 }
194}
195
196impl Sentinel for Template {
197 fn abort(rocket: &Rocket<Ignite>) -> bool {
198 if rocket.state::<ContextManager>().is_none() {
199 error!(
200 "returning `Template` responder without attaching `Templating::new()`.\n\
201 To use or query templates, you must attach `Templating::new()`.\n\
202 See the `Templating` documentation for more information."
203 );
204
205 return true;
206 }
207
208 false
209 }
210}
211
212/// A macro to easily create a template rendering context.
213///
214/// Invocations of this macro expand to a value of an anonymous type which
215/// implements [`Serialize`]. Fields can be literal expressions or variables
216/// captured from a surrounding scope, as long as all fields implement
217/// `Serialize`.
218///
219/// # Examples
220///
221/// The following code:
222///
223/// ```rust
224/// # #[macro_use] extern crate rocket;
225/// # use rocket_dyn_templates::{Template, context};
226/// #[get("/<foo>")]
227/// fn render_index(foo: u64) -> Template {
228/// Template::render("index.html", context! {
229/// // Note that shorthand field syntax is supported.
230/// // This is equivalent to `foo: foo,`
231/// foo,
232/// bar: "Hello world",
233/// })
234/// }
235/// ```
236///
237/// is equivalent to the following, but without the need to manually define an
238/// `IndexContext` struct:
239///
240/// ```rust
241/// # use rocket_dyn_templates::Template;
242/// # use rocket::serde::Serialize;
243/// # use rocket::get;
244/// #[derive(Serialize)]
245/// # #[serde(crate = "rocket::serde")]
246/// struct IndexContext<'a> {
247/// foo: u64,
248/// bar: &'a str,
249/// }
250///
251/// #[get("/<foo>")]
252/// fn render_index(foo: u64) -> Template {
253/// Template::render("index.html", IndexContext {
254/// foo,
255/// bar: "Hello world",
256/// })
257/// }
258/// ```
259///
260/// ## Nesting
261///
262/// Nested objects can be created by nesting calls to `context!`:
263///
264/// ```rust
265/// # use rocket_dyn_templates::context;
266/// # fn main() {
267/// let ctx = context! {
268/// planet: "Earth",
269/// info: context! {
270/// mass: 5.97e24,
271/// radius: "6371 km",
272/// moons: 1,
273/// },
274/// };
275/// # }
276/// ```
277#[macro_export]
278macro_rules! context {
279 ($($key:ident $(: $value:expr)?),*$(,)?) => {{
280 use $crate::serde::ser::{Serialize, Serializer, SerializeMap};
281 use ::std::fmt::{Debug, Formatter};
282 use ::std::result::Result;
283
284 #[allow(non_camel_case_types)]
285 struct ContextMacroCtxObject<$($key: Serialize),*> {
286 $($key: $key),*
287 }
288
289 #[allow(non_camel_case_types)]
290 impl<$($key: Serialize),*> Serialize for ContextMacroCtxObject<$($key),*> {
291 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
292 where S: Serializer,
293 {
294 let mut map = serializer.serialize_map(None)?;
295 $(map.serialize_entry(stringify!($key), &self.$key)?;)*
296 map.end()
297 }
298 }
299
300 #[allow(non_camel_case_types)]
301 impl<$($key: Debug + Serialize),*> Debug for ContextMacroCtxObject<$($key),*> {
302 fn fmt(&self, f: &mut Formatter<'_>) -> ::std::fmt::Result {
303 f.debug_struct("context!")
304 $(.field(stringify!($key), &self.$key))*
305 .finish()
306 }
307 }
308
309 ContextMacroCtxObject {
310 $($key $(: $value)?),*
311 }
312 }};
313}
314
315#[cfg(test)]
316mod tests {
317 use super::is_name_without_extension;
318
319 #[test]
320 fn name_without_extension() {
321 assert!(is_name_without_extension("index", "index.html"));
322 assert!(is_name_without_extension("dir/index", "dir/index.html"));
323 assert!(is_name_without_extension("index.template", "index.template.html"));
324
325 assert!(!is_name_without_extension("index", "index"));
326 assert!(!is_name_without_extension("index", "index."));
327 assert!(!is_name_without_extension("index", "indexes.html"));
328 assert!(!is_name_without_extension("index", "index.template.html"));
329 assert!(!is_name_without_extension("index", "index.d/page"));
330 assert!(!is_name_without_extension("index.html", "index"));
331 }
332}