pub struct TEMPLATES { /* private fields */ }
Methods from Deref<Target = Tera>§
Sourcepub fn check_macro_files(&self) -> Result<(), Error>
pub fn check_macro_files(&self) -> Result<(), Error>
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 build_inheritance_chains()
, you don’t usually need to call that yourself.
Sourcepub fn render(
&self,
template_name: &str,
context: &Context,
) -> Result<String, Error>
pub fn render( &self, template_name: &str, context: &Context, ) -> Result<String, Error>
Renders a Tera template given a Context
.
§Examples
Basic usage:
// Create new tera instance with sample template
let mut tera = Tera::default();
tera.add_raw_template("info", "My age is {{ age }}.");
// Create new context
let mut context = Context::new();
context.insert("age", &18);
// Render template using the context
let output = tera.render("info", &context).unwrap();
assert_eq!(output, "My age is 18.");
To render a template with an empty context, simply pass an empty Context
object.
// Create new tera instance with demo template
let mut tera = Tera::default();
tera.add_raw_template("hello.html", "<h1>Hello</h1>");
// Render a template with an empty context
let output = tera.render("hello.html", &Context::new()).unwrap();
assert_eq!(output, "<h1>Hello</h1>");
Sourcepub fn render_to(
&self,
template_name: &str,
context: &Context,
write: impl Write,
) -> Result<(), Error>
pub fn render_to( &self, template_name: &str, context: &Context, write: impl Write, ) -> Result<(), Error>
Renders a Tera template given a Context
to something that implements Write
.
The only difference from render()
is that this version doesn’t convert
buffer to a String, allowing to render directly to anything that implements Write
. For
example, this could be used to write directly to a File
.
Any I/O error will be reported in the result.
§Examples
Rendering into a Vec<u8>
:
let mut tera = Tera::default();
tera.add_raw_template("index.html", "<p>{{ name }}</p>");
// Rendering a template to an internal buffer
let mut buffer = Vec::new();
let mut context = Context::new();
context.insert("name", "John Wick");
tera.render_to("index.html", &context, &mut buffer).unwrap();
assert_eq!(buffer, b"<p>John Wick</p>");
Sourcepub fn get_template_names(&self) -> impl Iterator<Item = &str>
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"));