rocket_dyn_templates/engine/mod.rs
1use std::path::Path;
2use std::collections::HashMap;
3
4use rocket::serde::Serialize;
5
6use crate::template::TemplateInfo;
7
8#[cfg(feature = "tera")]
9mod tera;
10#[cfg(feature = "tera")]
11use ::tera::Tera;
12
13#[cfg(feature = "handlebars")]
14mod handlebars;
15#[cfg(feature = "handlebars")]
16use ::handlebars::Handlebars;
17
18#[cfg(feature = "minijinja")]
19mod minijinja;
20#[cfg(feature = "minijinja")]
21use ::minijinja::Environment;
22
23pub(crate) trait Engine: Send + Sync + Sized + 'static {
24 const EXT: &'static str;
25
26 fn init<'a>(templates: impl Iterator<Item = (&'a str, &'a Path)>) -> Self;
27 fn load<'a>(&mut self, templates: impl Iterator<Item = (&'a str, &'a Path)>) -> Option<()>;
28 fn render<C: Serialize>(&self, name: &str, context: C) -> Option<String>;
29}
30
31/// A structure exposing access to templating engines.
32///
33/// Calling methods on the exposed template engine types may require importing
34/// types from the respective templating engine library. These types should be
35/// imported from the reexported crate at the root of `rocket_dyn_templates` to
36/// avoid version mismatches. For instance, when registering a Tera filter, the
37/// [`tera::Value`] and [`tera::TeraResult`] types are required. Import them
38/// from `rocket_dyn_templates::tera`. The example below illustrates this:
39///
40/// ```rust
41/// # #[cfg(feature = "tera")] {
42/// use rocket_dyn_templates::{Templating, Engines};
43/// use rocket_dyn_templates::tera::{Value, Kwargs, State, TeraResult};
44///
45/// fn my_filter(value: &Value, _: Kwargs, _: &State) -> TeraResult<Value> {
46/// # /*
47/// ...
48/// # */ unimplemented!();
49/// }
50///
51/// fn main() {
52/// rocket::build()
53/// // ...
54/// .attach(Templating::init(|engines: &mut Engines| {
55/// engines.tera.register_filter("my_filter", my_filter);
56/// }))
57/// // ...
58/// # ;
59/// }
60/// # }
61/// ```
62///
63/// [`tera::Value`]: https://docs.rs/tera/2/tera/struct.Value.html
64/// [`tera::TeraResult`]: https://docs.rs/tera/2/tera/type.TeraResult.html
65pub struct Engines {
66 /// A `Tera` templating engine.
67 ///
68 /// This field is only available when the `tera` feature is enabled. When
69 /// calling methods on the `Tera` instance, ensure you use types imported
70 /// from `rocket_dyn_templates::tera` to avoid version mismatches.
71 ///
72 /// # Escaping
73 ///
74 /// HTML escaping is enabled for template names ending in `.html`, `.htm`,
75 /// `.xml`, `.xhtml`, or `.svg`, regardless of ASCII case, optionally
76 /// followed by `.tera`. Included templates use the escaping policy of the
77 /// template that includes them. To change these defaults, call
78 /// [`Tera::autoescape_on()`] or [`Tera::set_escape_fn()`] from a
79 /// [`Templating::init()`] callback.
80 ///
81 /// Only the template's _name_ is considered. A template added from a file
82 /// under a different name, as with `add_template_file(path, Some(name))`,
83 /// is escaped only if `name` ends in one of the extensions above,
84 /// regardless of the file's extension.
85 ///
86 /// # Template Loading
87 ///
88 /// Tera checks a template as soon as it's added: every filter, test,
89 /// function, component, and template it uses must already exist.
90 /// Similarly, delimiters cannot be changed once a template has been added.
91 /// As a result, the order of [`Templating`] callbacks matters for Tera.
92 /// See [customization](crate::Templating#customization) for which to use.
93 ///
94 /// Templates added together can use each other: Rocket adds all templates
95 /// in `template_dir` at once, as does [`Tera::add_raw_templates()`]. A
96 /// template in `template_dir` cannot, however, use a template added in an
97 /// `on_load` callback. If templates must use each other in both
98 /// directions, place them all in `template_dir`.
99 ///
100 /// [`Templating`]: crate::Templating
101 /// [`Templating::init()`]: crate::Templating::init()
102 #[cfg(feature = "tera")]
103 pub tera: Tera,
104
105 /// The Handlebars templating engine.
106 ///
107 /// This field is only available when the `handlebars` feature is enabled.
108 /// When calling methods on the `Handlebars` instance, ensure you use types
109 /// imported from `rocket_dyn_templates::handlebars` to avoid version
110 /// mismatches.
111 ///
112 /// Handlebars uses HTML escaping regardless of the template name. To
113 /// change this default, call [`Handlebars::register_escape_fn()`] from a
114 /// [`Templating::init()`](crate::Templating::init()) callback.
115 ///
116 /// Handlebars parses a template when it's added but looks up helpers and
117 /// partials only when rendering. As such, Handlebars templates can use
118 /// helpers and templates registered in either
119 /// [`Templating`](crate::Templating) callback.
120 #[cfg(feature = "handlebars")]
121 pub handlebars: Handlebars<'static>,
122
123 /// The minijinja templating engine.
124 ///
125 /// This field is only available when the `minijinja` feature is enabled.
126 /// When calling methods on the [`Environment`] instance, ensure you use
127 /// types imported from `rocket_dyn_templates::minijinja` to avoid version
128 /// mismatches.
129 ///
130 /// # Escaping
131 ///
132 /// HTML escaping is enabled for template names ending in `.html`, `.htm`,
133 /// `.xml`, `.xhtml`, or `.svg`, regardless of ASCII case. The lowercase
134 /// extensions `.json`, `.json5`, `.js`, `.yaml`, and `.yml` enable JSON
135 /// escaping. A final `.j2`, `.jinja`, or `.jinja2` extension is ignored.
136 ///
137 /// Included templates use their own escaping policy. As such, HTML
138 /// fragments should use an HTML extension: including a text template in an
139 /// HTML template can render values without escaping them. To change these
140 /// defaults, call [`Environment::set_auto_escape_callback()`] from a
141 /// [`Templating::init()`](crate::Templating::init()) callback.
142 ///
143 /// # Template Loading
144 ///
145 /// MiniJinja parses templates in `template_dir` when they are first
146 /// rendered, not when Rocket loads them, and looks up filters, tests,
147 /// functions, and other templates only when rendering. As such, MiniJinja
148 /// templates can use anything registered in either
149 /// [`Templating`](crate::Templating) callback. A template added via
150 /// [`Environment::add_template()`], however, is parsed immediately using
151 /// the current syntax and escaping settings, so configure these first.
152 ///
153 /// Because templates in `template_dir` are parsed when rendered, a syntax
154 /// error is only reported then. Rocket cannot detect such an error when it
155 /// reloads templates, so the previous templates are not restored.
156 ///
157 /// Rocket loads templates in `template_dir` via the environment's loader
158 /// and reloads them in debug mode, so MiniJinja's own automatic reloading
159 /// is disabled. Replacing the loader via [`Environment::set_loader()`]
160 /// makes templates in `template_dir` unavailable.
161 #[cfg(feature = "minijinja")]
162 pub minijinja: Environment<'static>,
163}
164
165impl Engines {
166 pub(crate) const ENABLED_EXTENSIONS: &'static [&'static str] = &[
167 #[cfg(feature = "tera")] Tera::EXT,
168 #[cfg(feature = "handlebars")] Handlebars::EXT,
169 #[cfg(feature = "minijinja")] Environment::EXT,
170 ];
171
172 fn files<E: Engine>(
173 templates: &HashMap<String, TemplateInfo>
174 ) -> impl Iterator<Item = (&str, &Path)> {
175 templates.iter()
176 .filter(|&(_, info)| info.engine_ext == E::EXT)
177 .filter_map(|(name, info)| Some((name.as_str(), info.path.as_deref()?)))
178 }
179
180 pub(crate) fn init(templates: &HashMap<String, TemplateInfo>) -> Engines {
181 Engines {
182 #[cfg(feature = "tera")]
183 tera: Tera::init(Self::files::<Tera>(templates)),
184 #[cfg(feature = "handlebars")]
185 handlebars: Handlebars::init(Self::files::<Handlebars<'static>>(templates)),
186 #[cfg(feature = "minijinja")]
187 minijinja: Environment::init(Self::files::<Environment<'static>>(templates)),
188 }
189 }
190
191 pub(crate) fn load(&mut self, templates: &HashMap<String, TemplateInfo>) -> Option<()> {
192 #[cfg(feature = "tera")]
193 self.tera.load(Self::files::<Tera>(templates))?;
194 #[cfg(feature = "handlebars")]
195 self.handlebars.load(Self::files::<Handlebars<'static>>(templates))?;
196 #[cfg(feature = "minijinja")]
197 self.minijinja.load(Self::files::<Environment<'static>>(templates))?;
198 Some(())
199 }
200
201 pub(crate) fn render<C: Serialize>(
202 &self,
203 name: &str,
204 info: &TemplateInfo,
205 context: C
206 ) -> Option<String> {
207 #[cfg(feature = "tera")] {
208 if info.engine_ext == Tera::EXT {
209 return Engine::render(&self.tera, name, context);
210 }
211 }
212
213 #[cfg(feature = "handlebars")] {
214 if info.engine_ext == Handlebars::EXT {
215 return Engine::render(&self.handlebars, name, context);
216 }
217 }
218
219 #[cfg(feature = "minijinja")] {
220 if info.engine_ext == Environment::EXT {
221 return Engine::render(&self.minijinja, name, context);
222 }
223 }
224
225 None
226 }
227
228 /// Returns iterator over template (name, engine_extension).
229 pub(crate) fn templates(&self) -> impl Iterator<Item = (&str, &'static str)> {
230 #[cfg(feature = "tera")]
231 let tera = self.tera.get_template_names().map(|name| (name, Tera::EXT));
232
233 #[cfg(feature = "handlebars")]
234 let handlebars = self.handlebars.get_templates().keys()
235 .map(|name| (name.as_str(), Handlebars::EXT));
236
237 #[cfg(feature = "minijinja")]
238 let minijinja = self.minijinja.templates()
239 .map(|(name, _)| (name, Environment::EXT));
240
241 #[cfg(not(feature = "tera"))] let tera = std::iter::empty();
242 #[cfg(not(feature = "handlebars"))] let handlebars = std::iter::empty();
243 #[cfg(not(feature = "minijinja"))] let minijinja = std::iter::empty();
244
245 tera.chain(handlebars).chain(minijinja)
246 }
247}