Skip to main content

rocket_dyn_templates/
lib.rs

1//! Dynamic templating engine support for Rocket.
2//!
3//! This crate adds support for dynamic template rendering to Rocket. It
4//! automatically discovers templates, provides a `Responder` to render
5//! templates, and automatically reloads templates when compiled in debug mode.
6//! At present, it supports [Handlebars], [Tera], and [MiniJinja].
7//!
8//! # Usage
9//!
10//!   1. Depend on `rocket_dyn_templates`. Enable the feature(s) corresponding
11//!      to your templating engine(s) of choice:
12//!
13//!      ```toml
14//!      [dependencies.rocket_dyn_templates]
15//!      version = "=0.4.0-rc.1"
16//!      features = ["handlebars", "tera", "minijinja"]
17//!      ```
18//!
19//!   2. Write your templates inside of the [configurable]
20//!      `${ROCKET_ROOT}/templates`. The filename _must_ end with an extension
21//!      corresponding to an enabled engine. The second-to-last extension should
22//!      correspond to the file's type:
23//!
24//!      | Engine       | Extension | Example                                    |
25//!      |--------------|-----------|--------------------------------------------|
26//!      | [Tera]       | `.tera`   | `${ROCKET_ROOT}/templates/index.html.tera` |
27//!      | [Handlebars] | `.hbs`    | `${ROCKET_ROOT}/templates/index.html.hbs`  |
28//!      | [MiniJinja]  | `.j2`     | `${ROCKET_ROOT}/templates/index.html.j2`   |
29//!
30//!      [configurable]: #configuration
31//!      [Tera]: https://docs.rs/crate/tera/2
32//!      [Handlebars]: https://docs.rs/crate/handlebars/6
33//!      [MiniJinja]: https://docs.rs/minijinja/3
34//!
35//!   3. Attach `Templating::new()` and return a [`Template`] from your routes
36//!      via [`Template::render()`], supplying the name of the template file
37//!      **minus the engine extension**:
38//!
39//!      ```rust
40//!      # #[macro_use] extern crate rocket;
41//!      use rocket_dyn_templates::{Template, Templating, context};
42//!
43//!      #[get("/")]
44//!      fn index() -> Template {
45//!          Template::render("index.html", context! { field: "value" })
46//!      }
47//!
48//!      #[launch]
49//!      fn rocket() -> _ {
50//!          rocket::build().attach(Templating::new())
51//!      }
52//!      ```
53//!
54//! ## Configuration
55//!
56//! This crate reads one configuration parameter from the configured figment:
57//!
58//!   * `template_dir` (**default: `templates/`**)
59//!
60//!      A path to a directory to search for template files in. Relative paths
61//!      are considered relative to the configuration file, or there is no file,
62//!      the current working directory.
63//!
64//! For example, to change the default and set `template_dir` to different
65//! values based on whether the application was compiled for debug or release
66//! from a `Rocket.toml` file (read by the default figment), you might write:
67//!
68//! ```toml
69//! [debug]
70//! template_dir = "static/templates"
71//!
72//! [release]
73//! template_dir = "/var/opt/www/templates"
74//! ```
75//!
76//! **Note:** `template_dir` defaults to `templates/`. It _does not_ need to be
77//! specified if the default suffices.
78//!
79//! See the [configuration chapter] of the guide for more information on
80//! configuration.
81//!
82//! [configuration chapter]: https://rocket.rs/v0.6-rc/guide/configuration
83//!
84//! ## Template Naming and Content-Types
85//!
86//! Templates are rendered by _name_ via [`Template::render()`], which returns a
87//! [`Template`] responder. The _name_ of the template is the path to the
88//! template file, relative to `template_dir`, minus the engine extension.
89//!
90//! The `Content-Type` of the response is automatically determined by the
91//! non-engine extension using [`ContentType::from_extension()`]. If there is no
92//! such extension or it is unknown, `text/plain` is used.
93//!
94//! The following table contains examples:
95//!
96//! | template path                                 | [`Template::render()`] call            | content-type |
97//! |-----------------------------------------------|----------------------------------------|--------------|
98//! | {template_dir}/index.html.hbs                 | `render("index.html")`                 | HTML         |
99//! | {template_dir}/index.tera                     | `render("index")`                      | `text/plain` |
100//! | {template_dir}/index.hbs                      | `render("index")`                      | `text/plain` |
101//! | {template_dir}/dir/index.hbs                  | `render("dir/index")`                  | `text/plain` |
102//! | {template_dir}/dir/data.json.tera             | `render("dir/data.json")`              | JSON         |
103//! | {template_dir}/data.template.xml.hbs          | `render("data.template.xml")`          | XML          |
104//! | {template_dir}/subdir/index.template.html.hbs | `render("subdir/index.template.html")` | HTML         |
105//!
106//! The recommended naming scheme is to use two extensions: one for the file
107//! type, and one for the template extension. This means that template
108//! extensions should look like: `.html.hbs`, `.html.tera`, `.xml.hbs`, and so
109//! on.
110//!
111//! [`ContentType::from_extension()`]: ../rocket/http/struct.ContentType.html#method.from_extension
112//!
113//! ### Rendering Context
114//!
115//! In addition to a name, [`Template::render()`] requires a context to use
116//! during rendering. The context can be any
117//! [`Serialize`](rocket::serde::Serialize) type that serializes to an `Object`
118//! (a dictionary) value. The [`context!`] macro can be used to create inline
119//! `Serialize`-able context objects.
120//!
121//! ```rust
122//! # #[macro_use] extern crate rocket;
123//! use rocket::serde::Serialize;
124//! use rocket_dyn_templates::{Template, context};
125//!
126//! #[get("/")]
127//! fn index() -> Template {
128//!     // Using the `context! { }` macro.
129//!     Template::render("index.html", context! {
130//!         site_name: "Rocket - Home Page",
131//!         version: 127,
132//!     })
133//! }
134//!
135//! #[get("/")]
136//! fn index2() -> Template {
137//!     #[derive(Serialize)]
138//!     #[serde(crate = "rocket::serde")]
139//!     struct IndexContext {
140//!         site_name: &'static str,
141//!         version: u8
142//!     }
143//!
144//!     // Using an existing `IndexContext`, which implements `Serialize`.
145//!     Template::render("index.html", IndexContext {
146//!         site_name: "Rocket - Home Page",
147//!         version: 127,
148//!     })
149//! }
150//! ```
151//!
152//! ### Discovery, Automatic Reloads, and Engine Customization
153//!
154//! As long as a [`Templating`] fairing is [attached], any file in the
155//! configured `template_dir` ending with a known engine extension (as described
156//! in the [usage section](#usage)) can be rendered. The fairing also allows
157//! customizing the templating engines, for instance, to register helpers or
158//! templates from strings. See [`Templating`] for details.
159//!
160//! _**Note:** Templates that are registered directly with an engine use
161//! whatever name is provided during registration; no extensions are
162//! automatically removed._
163//!
164//! In debug mode (without the `--release` flag passed to `cargo`), templates
165//! are **automatically reloaded** from disk when changes are made. In release
166//! builds, Rocket's automatic reloading is disabled to improve performance and
167//! cannot be enabled.
168//!
169//! [attached]: rocket::Rocket::attach()
170//!
171//! ### Metadata and Rendering to `String`
172//!
173//! The [`Metadata`] request guard allows dynamically querying templating
174//! metadata, such as whether a template is known to exist
175//! ([`Metadata::contains_template()`]), and to render templates to `String`
176//! ([`Metadata::render()`]).
177
178#![doc(html_root_url = "https://api.rocket.rs/v0.6-rc/rocket_dyn_templates")]
179#![doc(html_favicon_url = "https://rocket.rs/images/favicon.ico")]
180#![doc(html_logo_url = "https://rocket.rs/images/logo-boxed.png")]
181
182// Without an engine, the engine plumbing is unused.
183#![cfg_attr(
184    not(any(feature = "tera", feature = "handlebars", feature = "minijinja")),
185    allow(dead_code, unused_variables)
186)]
187
188#[macro_use] extern crate rocket;
189
190#[doc(inline)]
191#[cfg(feature = "tera")]
192/// The tera templating engine library, reexported.
193pub use tera;
194
195#[doc(inline)]
196#[cfg(feature = "handlebars")]
197/// The handlebars templating engine library, reexported.
198pub use handlebars;
199
200#[doc(inline)]
201#[cfg(feature = "minijinja")]
202/// The minijinja templating engine library, reexported.
203pub use minijinja;
204
205#[doc(hidden)]
206pub use rocket::serde;
207
208mod engine;
209mod fairing;
210mod context;
211mod metadata;
212mod template;
213
214pub use engine::Engines;
215pub use fairing::Templating;
216pub use metadata::Metadata;
217pub use template::Template;