Skip to main content

Crate rocket_tera

Crate rocket_tera 

Source
Expand description

Tera templating support for Rocket.

This crate adds support for using Tera with Rocket. It automatically discovers templates, provides a Responder to render templates, and automatically reloads templates when compiled in debug mode.

§Usage

  1. Depend on the crate: cargo add rocket_tera

  2. Write your templates inside of the configurable ${ROCKET_ROOT}/templates. Every file in that directory is a template; no particular extension is required, but the extension determines the response’s Content-Type, as in ${ROCKET_ROOT}/templates/index.html.

  3. Attach Template::fairing() and return a Template from your routes via Template::render(), supplying the path of the template file relative to the template directory:

    use rocket_tera::{Template, context};
    
    #[get("/")]
    fn index() -> Template {
        Template::render("index.html", context! { field: "value" })
    }
    
    #[launch]
    fn rocket() -> _ {
        rocket::build().attach(Template::fairing())
    }

§Configuration

This crate reads one configuration parameter from the configured figment:

  • template_dir (default: templates/)

    A path to a directory to search for template files in. Relative paths are considered relative to the configuration file, or if there is no file, the current working directory.

For example, to change the default and set template_dir to different values based on whether the application was compiled for debug or release from a Rocket.toml file (read by the default figment), you might write:

[debug]
template_dir = "static/templates"

[release]
template_dir = "/var/opt/www/templates"

Note: template_dir defaults to templates/. It does not need to be specified if the default suffices.

See the configuration chapter of the guide for more information on configuration.

§Template Naming and Content-Types

Templates are rendered by name via Template::render(), which returns a Template responder. The name of the template is the path to the template file, relative to template_dir, extension included.

The Content-Type of the response is automatically determined by the extension using ContentType::from_extension(). If there is no extension or it is unknown, text/plain is used.

The following table contains examples:

template pathTemplate::render() callcontent-type
{template_dir}/index.htmlrender("index.html")HTML
{template_dir}/indexrender("index")text/plain
{template_dir}/dir/indexrender("dir/index")text/plain
{template_dir}/dir/data.jsonrender("dir/data.json")JSON
{template_dir}/data.template.xmlrender("data.template.xml")XML
{template_dir}/subdir/index.template.htmlrender("subdir/index.template.html")HTML

Give every template the extension of the file type it renders to, so that the Content-Type is correct: .html, .xml, and so on.

§Rendering Context

In addition to a name, Template::render() requires a context to use during rendering. The context can be any Serialize type that serializes to an Object (a dictionary) value. The context! macro can be used to create inline Serialize-able context objects.

use rocket::serde::Serialize;
use rocket_tera::{Template, context};

#[get("/")]
fn index() -> Template {
    // Using the `context! { }` macro.
    Template::render("index.html", context! {
        site_name: "Rocket - Home Page",
        version: 127,
    })
}

#[get("/")]
fn index2() -> Template {
    #[derive(Serialize)]
    #[serde(crate = "rocket::serde")]
    struct IndexContext {
        site_name: &'static str,
        version: u8
    }

    // Using an existing `IndexContext`, which implements `Serialize`.
    Template::render("index.html", IndexContext {
        site_name: "Rocket - Home Page",
        version: 127,
    })
}

§Discovery, Automatic Reloads, and Engine Customization

As long as one of Template::fairing(), Template::custom(), or Template::try_custom() is attached, every file in the configured template_dir is registered with Tera and can be rendered. Files that are not valid Tera templates will abort the launch, so keep non-template assets out of template_dir.

Note: Templates that are registered directly via Template::custom() use whatever name was provided during that registration.

In debug mode (without the --release flag passed to cargo), templates are automatically reloaded from disk when changes are made. In release builds, template reloading is disabled to improve performance and cannot be enabled.

§tera-contrib Features

Tera 2 moved builtin features that required other dependencies to the tera-contrib crate. Enabling a contrib-* feature here enables and registers the matching tera-contrib feature:

FeatureRegisters
contrib-base64b64_encode, b64_decode filters
contrib-datedate filter, now function, before / after tests
contrib-filesize_formatfilesize_format filter
contrib-formatformat filter
contrib-jsonjson_encode filter
contrib-randget_random function, shuffle filter
contrib-regexstriptags, spaceless, regex_replace filters, matching test
contrib-slugslug filter
contrib-urlencodeurlencode, urlencode_strict filters

§Metadata and Rendering to String

The Metadata request guard allows dynamically querying templating metadata, such as whether a template is known to exist (Metadata::contains_template()), and to render templates to String (Metadata::render()).

Modules§

tera
The tera templating engine library, reexported.

Macros§

context
A macro to easily create a template rendering context.

Structs§

Metadata
Request guard for dynamically querying template metadata.
Template
Responder that renders a dynamic template.