rocket_dyn_templates/fairing.rs
1use rocket::{Rocket, Build, Orbit};
2use rocket::fairing::{self, Fairing, Info, Kind};
3use rocket::figment::{Source, value::magic::RelativePathBuf};
4use rocket::trace::Trace;
5
6use crate::context::{Callback, Context, ContextManager};
7use crate::template::DEFAULT_TEMPLATE_DIR;
8use crate::engine::Engines;
9
10/// A fairing that initializes and maintains templating state.
11///
12/// # Usage
13///
14/// To use `Templating`, first construct an instance with [`Templating::new()`]
15/// or [`Templating::init()`]. The former uses the default configuration, while
16/// the latter allows you to customize the templating engines. Then, attach the
17/// instance to your application's instance of `Rocket`:
18///
19/// ```rust
20/// use rocket_dyn_templates::Templating;
21///
22/// rocket::build()
23/// // ...
24/// .attach(Templating::new())
25/// # ;
26/// ```
27///
28/// This fairing _must_ be attached to any `Rocket` instance that wishes to
29/// render templates. Failure to attach this fairing will result in an
30/// "Uninitialized template context: missing fairing." error message when a
31/// template is attempted to be rendered.
32///
33/// # Customization
34///
35/// Templating engines can be customized via two callbacks: one set via
36/// [`Templating::init()`] or [`on_init()`](Self::on_init()), and another set
37/// via [`on_load()`](Self::on_load()). Each is passed an [`Engines`], which
38/// exposes the enabled engines. Regardless of the order in which the callbacks
39/// are set, the fairing initializes templating as follows:
40///
41/// 1. Creates the templating engines with Rocket's defaults.
42/// 2. Calls the `on_init` callback.
43/// 3. Loads the templates in `template_dir`.
44/// 4. Calls the `on_load` callback.
45///
46/// Which callback to use depends on the templates in `template_dir`. Some
47/// engines check a template as soon as it's added, requiring everything it
48/// uses, such as filters and other templates, to already exist. As such,
49/// anything that templates in `template_dir` use must be registered in
50/// `on_init`, before those templates are loaded. Conversely, a template that
51/// uses templates in `template_dir` must be added in `on_load`, after those
52/// templates are loaded. In summary:
53///
54/// | To... | Use |
55/// |------------------------------------------------------|-----------|
56/// | register helpers, filters, functions, or tests | `on_init` |
57/// | configure syntax, escaping, or other engine settings | `on_init` |
58/// | add a template used by templates in `template_dir` | `on_init` |
59/// | add a template that uses templates in `template_dir` | `on_load` |
60///
61/// As a general rule of thumb, use `on_init`. Only use `on_load` to add
62/// templates that extend, include, or otherwise use templates in
63/// `template_dir`. See [`Engines`] for details on when each engine checks
64/// templates.
65///
66/// For example, the following adds two Tera templates: `footer.html`, which
67/// templates in `template_dir` can include, and `child.html`, which extends
68/// `base.html`, a template in `template_dir`:
69///
70/// ```rust
71/// # #[cfg(feature = "tera")] {
72/// use rocket_dyn_templates::Templating;
73///
74/// let templating = Templating::try_init(|engines| {
75/// engines.tera.add_raw_template("footer.html", "<footer>Rocket</footer>")?;
76/// Ok(())
77/// }).try_on_load(|engines| {
78/// engines.tera.add_raw_template("child.html", concat!(
79/// "{% extends \"base.html\" %}",
80/// "{% block content %}Hello, world!{% endblock %}",
81/// ))?;
82///
83/// Ok(())
84/// });
85///
86/// rocket::build().attach(templating);
87/// # }
88/// ```
89///
90/// # Reloading
91///
92/// In debug mode, the fairing checks for modifications to templates before
93/// every request and reloads them if necessary. Reloading repeats all of the
94/// steps above with new engines, so both callbacks are called again.
95///
96/// # Errors
97///
98/// If loading templates or a callback fails, the remaining steps are skipped.
99/// During ignition, this aborts launch. During reloading, the new engines are
100/// discarded, and the previous templates continue to be used.
101pub struct Templating {
102 init: Option<Callback>,
103 load: Option<Callback>,
104}
105
106impl Templating {
107 /// Returns a fairing that initializes and maintains templating state.
108 ///
109 /// If you wish to customize the internal templating engines, use
110 /// [`Templating::init()`] instead.
111 ///
112 /// # Example
113 ///
114 /// To attach this fairing, simply call `attach` on the application's
115 /// `Rocket` instance with `Templating::new()`:
116 ///
117 /// ```rust
118 /// extern crate rocket;
119 /// extern crate rocket_dyn_templates;
120 ///
121 /// use rocket_dyn_templates::Templating;
122 ///
123 /// fn main() {
124 /// rocket::build()
125 /// // ...
126 /// .attach(Templating::new())
127 /// // ...
128 /// # ;
129 /// }
130 /// ```
131 pub fn new() -> Self {
132 Templating { init: None, load: None }
133 }
134
135 /// Returns a fairing that initializes and maintains templating state.
136 ///
137 /// Unlike [`Templating::new()`], this method allows you to customize the
138 /// templating engines via the function `f`, which is called before
139 /// templates are loaded. This is equivalent to
140 /// `Templating::new().on_init(f)`. See
141 /// [customization](Templating#customization) for details.
142 ///
143 /// This method does not allow the function `f` to fail. If `f` is fallible,
144 /// use [`Templating::try_init()`] instead.
145 ///
146 /// # Example
147 ///
148 /// ```rust
149 /// extern crate rocket;
150 /// extern crate rocket_dyn_templates;
151 ///
152 /// use rocket_dyn_templates::Templating;
153 ///
154 /// fn main() {
155 /// rocket::build()
156 /// // ...
157 /// .attach(Templating::init(|engines| {
158 /// // engines.handlebars.register_helper ...
159 /// }))
160 /// // ...
161 /// # ;
162 /// }
163 /// ```
164 pub fn init<F: Send + Sync + 'static>(f: F) -> Self
165 where F: Fn(&mut Engines)
166 {
167 Self::new().on_init(f)
168 }
169
170 /// Returns a fairing that initializes and maintains templating state.
171 ///
172 /// This variant of [`Templating::init()`] allows a fallible `f` and is
173 /// equivalent to `Templating::new().try_on_init(f)`. See
174 /// [errors](Templating#errors) for what happens when `f` fails.
175 ///
176 /// # Example
177 ///
178 /// ```rust
179 /// extern crate rocket;
180 /// extern crate rocket_dyn_templates;
181 ///
182 /// use rocket_dyn_templates::Templating;
183 ///
184 /// fn main() {
185 /// rocket::build()
186 /// // ...
187 /// .attach(Templating::try_init(|engines| {
188 /// // engines.handlebars.register_helper ...
189 /// Ok(())
190 /// }))
191 /// // ...
192 /// # ;
193 /// }
194 /// ```
195 pub fn try_init<F: Send + Sync + 'static>(f: F) -> Self
196 where F: Fn(&mut Engines) -> Result<(), Box<dyn std::error::Error>>
197 {
198 Self::new().try_on_init(f)
199 }
200
201 /// Sets the function `f` to be called before templates are loaded.
202 ///
203 /// Use this method to register helpers, configure engines, and add
204 /// templates that templates in `template_dir` use. See
205 /// [customization](Templating#customization) for details. If an `on_init`
206 /// callback was previously set, it is replaced with `f`.
207 ///
208 /// This method does not allow the function `f` to fail. If `f` is fallible,
209 /// use [`Templating::try_on_init()`] instead.
210 pub fn on_init<F: Send + Sync + 'static>(self, f: F) -> Self
211 where F: Fn(&mut Engines)
212 {
213 self.try_on_init(move |engines| { f(engines); Ok(()) })
214 }
215
216 /// Sets a fallible function `f` to be called before templates are loaded.
217 ///
218 /// This variant of [`Templating::on_init()`] allows a fallible `f`. See
219 /// [errors](Templating#errors) for what happens when `f` fails.
220 pub fn try_on_init<F: Send + Sync + 'static>(mut self, f: F) -> Self
221 where F: Fn(&mut Engines) -> Result<(), Box<dyn std::error::Error>>
222 {
223 self.init = Some(Box::new(f));
224 self
225 }
226
227 /// Sets the function `f` to be called after templates are loaded.
228 ///
229 /// Use this method to add templates that extend, include, or otherwise use
230 /// templates in `template_dir`. See
231 /// [customization](Templating#customization) for details. If an `on_load`
232 /// callback was previously set, it is replaced with `f`.
233 ///
234 /// This method does not allow the function `f` to fail. If `f` is fallible,
235 /// use [`Templating::try_on_load()`] instead.
236 pub fn on_load<F: Send + Sync + 'static>(self, f: F) -> Self
237 where F: Fn(&mut Engines)
238 {
239 self.try_on_load(move |engines| { f(engines); Ok(()) })
240 }
241
242 /// Sets a fallible function `f` to be called after templates are loaded.
243 ///
244 /// This variant of [`Templating::on_load()`] allows a fallible `f`. See
245 /// [errors](Templating#errors) for what happens when `f` fails.
246 pub fn try_on_load<F: Send + Sync + 'static>(mut self, f: F) -> Self
247 where F: Fn(&mut Engines) -> Result<(), Box<dyn std::error::Error>>
248 {
249 self.load = Some(Box::new(f));
250 self
251 }
252}
253
254impl Default for Templating {
255 fn default() -> Self {
256 Self::new()
257 }
258}
259
260#[rocket::async_trait]
261impl Fairing for Templating {
262 fn info(&self) -> Info {
263 let kind = Kind::Ignite | Kind::Liftoff;
264 #[cfg(debug_assertions)] let kind = kind | Kind::Request;
265
266 Info { kind, name: "Templating" }
267 }
268
269 /// Initializes the template context. Templates will be searched for in the
270 /// `template_dir` config variable or the default (`templates/`).
271 /// The user's callbacks, if any were supplied, are called to customize the
272 /// template engines. In debug mode, the `ContextManager::new` method
273 /// initializes a directory watcher for auto-reloading of templates.
274 async fn on_ignite(&self, rocket: Rocket<Build>) -> fairing::Result {
275 let configured_dir = rocket.figment()
276 .extract_inner::<RelativePathBuf>("template_dir")
277 .map(|path| path.relative());
278
279 let path = match configured_dir {
280 Ok(dir) => dir,
281 Err(e) if e.missing() => DEFAULT_TEMPLATE_DIR.into(),
282 Err(e) => {
283 e.trace_error();
284 return Err(rocket);
285 }
286 };
287
288 if let Some(ctxt) = Context::initialize(&path, self.init.as_ref(), self.load.as_ref()) {
289 Ok(rocket.manage(ContextManager::new(ctxt)))
290 } else {
291 error!("Template initialization failed. Aborting launch.");
292 Err(rocket)
293 }
294 }
295
296 async fn on_liftoff(&self, rocket: &Rocket<Orbit>) {
297 let cm = rocket.state::<ContextManager>()
298 .expect("Template ContextManager registered in on_ignite");
299
300 span_info!("templating" => {
301 info!(directory = %Source::from(&*cm.context().root));
302 info!(engines = ?Engines::ENABLED_EXTENSIONS);
303 });
304 }
305
306 #[cfg(debug_assertions)]
307 async fn on_request(&self, req: &mut rocket::Request<'_>, _data: &mut rocket::Data<'_>) {
308 let cm = req.rocket().state::<ContextManager>()
309 .expect("Template ContextManager registered in on_ignite");
310
311 cm.reload_if_needed(self.init.as_ref(), self.load.as_ref());
312 }
313}