Skip to main content

rocket_dyn_templates/
fairing.rs

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