Struct tera::Tera

source ·
pub struct Tera { /* private fields */ }
Expand description

The main point of interaction in this library.

Implementations§

source§

impl Tera

source

pub fn new(dir: &str) -> Result<Tera>

Create a new instance of Tera, containing all the parsed templates found in the dir glob

match Tera::new("templates/**/*") {
    Ok(t) => t,
    Err(e) => {
        println!("Parsing error(s): {}", e);
        ::std::process::exit(1);
    }
}
source

pub fn parse(dir: &str) -> Result<Tera>

Create a new instance of Tera, containing all the parsed templates found in the dir glob The difference with Tera::new is that it won’t build the inheritance chains automatically so you are free to modify the templates if you need to. You will NOT get a working Tera instance using Tera::parse, you will need to call tera.build_inheritance_chains() to make it usable

let mut tera = match Tera::parse("templates/**/*") {
    Ok(t) => t,
    Err(e) => {
        println!("Parsing error(s): {}", e);
        ::std::process::exit(1);
    }
};
tera.build_inheritance_chains()?;
source

pub fn build_inheritance_chains(&mut self) -> Result<()>

We need to know the hierarchy of templates to be able to render multiple extends level This happens at compile-time to avoid checking it every time we want to render a template This also checks for soundness issues in the inheritance chains, such as missing template or circular extends. It also builds the block inheritance chain and detects when super() is called in a place where it can’t possibly work

You generally don’t need to call that yourself, unless you used Tera::parse

source

pub fn check_macro_files(&self) -> Result<()>

We keep track of macro files loaded in each Template so we can know whether one or them is missing and error accordingly before the user tries to render a template.

As with self::build_inheritance_chains, you don’t usually need to call that yourself.

source

pub fn render(&self, template_name: &str, context: &Context) -> Result<String>

Renders a Tera template given a tera::Context,

To render a template with an empty context, simply pass a new tera::Context object

// Rendering a template with a normal context
let mut context = Context::new();
context.insert("age", 18);
tera.render("hello.html", context);
// Rendering a template with an empty context
let output = tera.render("hello.html", Context::new());
source

pub fn render_to( &self, template_name: &str, context: &Context, write: impl Write ) -> Result<()>

Renders a Tera template given a tera::Context to a std::io::Write,

The only difference from Self::render is that this version doesn’t convert buffer to a String, allowing to render directly to anything that implements std::io::Write.

Any i/o error will be reported in the result.

// Rendering a template to an internal buffer
let mut buffer = Vec::new();
let mut context = Context::new();
context.insert("age", 18);
tera.render_to("hello.html", context, &mut buffer);
source

pub fn render_str(&mut self, input: &str, context: &Context) -> Result<String>

Renders a one off template (for example a template coming from a user input) given a Context and an instance of Tera. This allows you to render templates using custom filters or functions.

Any errors will mention the __tera_one_off template: this is the name given to the template by Tera.

let mut context = Context::new();
context.insert("greeting", &"Hello");
let string = tera.render_str("{{ greeting }} World!", &context)?;
assert_eq!(string, "Hello World!");
source

pub fn one_off( input: &str, context: &Context, autoescape: bool ) -> Result<String>

Renders a one off template (for example a template coming from a user input) given a Context

This creates a separate instance of Tera with no possibilities of adding custom filters or testers, parses the template and render it immediately. Any errors will mention the __tera_one_off template: this is the name given to the template by Tera

let mut context = Context::new();
context.insert("greeting", &"hello");
Tera::one_off("{{ greeting }} world", &context, true);
source

pub fn get_template_names(&self) -> impl Iterator<Item = &str>

Returns an iterator over the names of all registered templates in an unspecified order.

Example
use tera::Tera;

let mut tera = Tera::default();
tera.add_raw_template("foo", "{{ hello }}");
tera.add_raw_template("another-one.html", "contents go here");

let names: Vec<_> = tera.get_template_names().collect();
assert_eq!(names.len(), 2);
assert!(names.contains(&"foo"));
assert!(names.contains(&"another-one.html"));
source

pub fn add_raw_template(&mut self, name: &str, content: &str) -> Result<()>

Add a single template to the Tera instance

This will error if the inheritance chain can’t be built, such as adding a child template without the parent one. If you want to add several templates, use Tera::add_templates

tera.add_raw_template("new.html", "Blabla");
source

pub fn add_raw_templates<I, N, C>(&mut self, templates: I) -> Result<()>where I: IntoIterator<Item = (N, C)>, N: AsRef<str>, C: AsRef<str>,

Add all the templates given to the Tera instance

This will error if the inheritance chain can’t be built, such as adding a child template without the parent one.

tera.add_raw_templates(vec![
    ("new.html", "blabla"),
    ("new2.html", "hello"),
]);
source

pub fn add_template_file<P: AsRef<Path>>( &mut self, path: P, name: Option<&str> ) -> Result<()>

Add a single template from a path to the Tera instance. The default name for the template is the path given, but this can be renamed with the name parameter

This will error if the inheritance chain can’t be built, such as adding a child template without the parent one. If you want to add several file, use Tera::add_template_files

// Use path as name
tera.add_template_file(path, None);
// Rename
tera.add_template_file(path, Some("index"));
source

pub fn add_template_files<I, P, N>(&mut self, files: I) -> Result<()>where I: IntoIterator<Item = (P, Option<N>)>, P: AsRef<Path>, N: AsRef<str>,

Add several templates from paths to the Tera instance. The default name for the template is the path given, but this can be renamed with the second parameter of the tuple

This will error if the inheritance chain can’t be built, such as adding a child template without the parent one.

tera.add_template_files(vec![
    (path1, None), // this template will have the value of path1 as name
    (path2, Some("hey")), // this template will have `hey` as name
]);
source

pub fn register_filter<F: Filter + 'static>(&mut self, name: &str, filter: F)

Register a filter with Tera.

If a filter with that name already exists, it will be overwritten

tera.register_filter("upper", string::upper);
source

pub fn register_tester<T: Test + 'static>(&mut self, name: &str, tester: T)

Register a tester with Tera.

If a tester with that name already exists, it will be overwritten

tera.register_tester("odd", testers::odd);
source

pub fn register_function<F: Function + 'static>( &mut self, name: &str, function: F )

Register a function with Tera.

If a function with that name already exists, it will be overwritten

tera.register_function("range", range);
source

pub fn autoescape_on(&mut self, suffixes: Vec<&'static str>)

Select which suffix(es) to automatically do HTML escaping on, [".html", ".htm", ".xml"] by default.

Only call this function if you wish to change the defaults.

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

pub fn set_escape_fn(&mut self, function: fn(_: &str) -> String)

Set user-defined function which applied to a rendered content.

 fn escape_c_string(input: &str) -> String { ... }

 // make valid C string literal
 tera.set_escape_fn(escape_c_string);
 tera.add_raw_template("foo", "\"{{ content }}\"").unwrap();
 tera.autoescape_on(vec!["foo"]);
 let mut context = Context::new();
 context.insert("content", &"Hello\n\'world\"!");
 let result = tera.render("foo", &context).unwrap();
 assert_eq!(result, r#""Hello\n\'world\"!""#);
source

pub fn reset_escape_fn(&mut self)

Reset escape function to default tera::escape_html.

source

pub fn full_reload(&mut self) -> Result<()>

Re-parse all templates found in the glob given to Tera Use this when you are watching a directory and want to reload everything, for example when a file is added.

If you are adding templates without using a glob, we can’t know when a template is deleted, which would result in an error if we are trying to reload that file

source

pub fn extend(&mut self, other: &Tera) -> Result<()>

Use that method when you want to add a given Tera instance templates/filters/testers/functions to your own. If a template/filter/tester/function with the same name already exists in your instance, it will not be overwritten.

 // add all the templates from FRAMEWORK_TERA
 // except the ones that have an identical name to the ones in `my_tera`
 my_tera.extend(&FRAMEWORK_TERA);

Trait Implementations§

source§

impl Clone for Tera

source§

fn clone(&self) -> Tera

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Tera

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Tera

source§

fn default() -> Tera

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Tera

§

impl Send for Tera

§

impl Sync for Tera

§

impl Unpin for Tera

§

impl !UnwindSafe for Tera

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V