Struct rocket_contrib::Template [] [src]

pub struct Template(_, _);

The Template type implements generic support for template rendering in Rocket.

Templating in Rocket words by first discovering all of the templates inside the template directory. The template directory is configurable via the template_dir configuration parameter and defaults to templates/. The path set in template_dir should be relative to the Rocket configuration file. See the configuration chapter of the guide for more information on configuration.

Templates are discovered according to their extension. At present, this library supports the following templates and extensions:

Any file that ends with one of these extension will be discovered and rendered with the corresponding templating engine. The name of the template will be the path to the template file relative to template_dir minus at most two extensions. The following are examples of template names (on the right) given that the template is at the path on the left.

The recommended naming scheme is to use two extensions: one for the file type, and one for the template extension. This means that template extensions should look like: .html.hbs, .html.tera, .xml.hbs, etc.

Templates are rendered with the render method. The method takes in the name of a template and a context to render the template with. The context can be any type that implements Serialize from Serde and would serialize to an Object value.


To use, add the handlebars_templates feature, the tera_templates feature, or both, to the rocket_contrib dependencies section of your Cargo.toml:

version = "*"
default-features = false
features = ["handlebars_templates", "tera_templates"]

The Template type implements Rocket's Responder trait, so it can be returned from a request handler directly:

fn index() -> Template {
    let context = ...;
    Template::render("index", &context)


impl Template

Render the template named name with the context context. The context can be of any type that implements Serialize. This is typically a HashMap or a custom struct.


use std::collections::HashMap;
use rocket_contrib::Template;

// Create a `context`. Here, just an empty `HashMap`.
let mut context = HashMap::new();

let template = Template::render("index", &context);

Trait Implementations

impl Debug for Template

Formats the value using the given formatter.

impl Responder<'static> for Template

Returns a response with the Content-Type derived from the template's extension and a fixed-size body containing the rendered template. If rendering fails, an Err of Status::InternalServerError is returned.

Returns Ok if a Response could be generated successfully. Otherwise, returns an Err with a failing Status. Read more

impl Display for Template

Renders self. If the template cannot be rendered, nothing is written.

Formats the value using the given formatter. Read more