Home Explore Blog CI



tera

1st chunk of `docs/content/docs/_index.md`
74fd7228d45738011511e37f97747323f0b4794a979519bf0000000100000fb4
+++
template = "docs.html"
insert_anchor_links = "right"
+++

# Getting started

To use Tera in your Rust projects, simply add it to your `Cargo.toml`:

```toml
tera = "1"
```

By default, Tera comes with some additional dependencies required for the `truncate`, `date`, `filesizeformat`, `slugify`, `urlencode` and `urlencode_strict` filters as
well as for the `now` function. You can disable them by setting the following in your `Cargo.toml`:

```toml
tera = { version = "1", default-features = false }
```


And add the following to your `lib.rs` or `main.rs` if you are not using Rust 2018 edition or later:

```rs
extern crate tera;
```

You can view everything Tera exports on the [API docs](https://docs.rs/tera).

# Usage

The primary method of using Tera is to load and parse all the templates in a given glob.

Let's take the following directory as example.

```sh
templates/
  hello.html
  index.html
  products/
    product.html
    price.html
```

Assuming the Rust file is at the same level as the `templates` folder, we can get a Tera instance that way:

```rs
use tera::Tera;

// Use globbing
let tera = match Tera::new("templates/**/*.html") {
    Ok(t) => t,
    Err(e) => {
        println!("Parsing error(s): {}", e);
        ::std::process::exit(1);
    }
};
```

Compiling templates is a step that is meant to only happen once: use something like [lazy_static](https://crates.io/crates/lazy_static)
to define a constant instance.

```rs
lazy_static! {
    pub static ref TEMPLATES: Tera = {
        let mut tera = match Tera::new("examples/basic/templates/**/*") {
            Ok(t) => t,
            Err(e) => {
                println!("Parsing error(s): {}", e);
                ::std::process::exit(1);
            }
        };
        tera.autoescape_on(vec![".html", ".sql"]);
        tera.register_filter("do_nothing", do_nothing_filter);
        tera
    };
}
```

You need two things to render a template: a name and a context.
If you are using globs, Tera will automatically remove the glob prefix from the template names. To use our example from before,
the template name for the file located at `templates/hello.html` will be `hello.html`.

The context can either be a data structure that implements the `Serialize` trait from `serde_json` or an instance of `tera::Context`:

```rs
use tera::Context;
// Using the tera Context struct
let mut context = Context::new();
context.insert("product", &product);
context.insert("vat_rate", &0.20);
tera.render("products/product.html", &context)?;

#[derive(Serialize)]
struct Product {
    name: String
}
// or a struct
tera.render("products/product.html", &Context::from_serialize(&product)?)?;
```

## Auto-escaping
By default, Tera will auto-escape all content in files ending with `".html"`, `".htm"` and `".xml"`.
Escaping follows the recommendations from [OWASP](https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet).

You can override that or completely disable auto-escaping by calling the `autoescape_on` method:

```rs
// escape only files ending with `.php.html`
tera.autoescape_on(vec![".php.html"]);
// disable autoescaping completely
tera.autoescape_on(vec![]);
```

Tera does not perform contextual auto-escaping, e.g. by parsing the template to know whether to escape JS, CSS or HTML (see 
<https://rawgit.com/mikesamuel/sanitized-jquery-templates/trunk/safetemplate.html> for more details on that).

## Advanced usage

### Extending another instance
If you are using a framework or a library using Tera, chances are they provide their own Tera instance with some
built-in templates, filters, global functions or testers. Tera offers an `extend` method that will extend your own
instance with everything mentioned before:

```rs
let mut tera = Tera::new(&tpl_glob).chain_err(|| "Error parsing templates")?;
// ZOLA_TERA is an instance present in a library
tera.extend(&ZOLA_TERA)?;
```
If anything - templates, filters, etc - with the same name exists in both instances, Tera will only keep yours.

Title: Getting Started with Tera: Installation and Usage
Summary
This section guides users on how to integrate Tera into Rust projects, including adding it to `Cargo.toml`, handling dependencies, and using the primary method of loading and parsing templates. It covers compiling templates using `lazy_static`, rendering templates with names and contexts, auto-escaping configurations, and extending Tera instances with built-in features from frameworks or libraries.