Struct minijinja::Environment
source · [−]pub struct Environment<'source> { /* private fields */ }
Expand description
An abstraction that holds the engine configuration.
This object holds the central configuration state for templates. It is also the container for all loaded templates.
The environment holds references to the source the templates were created from. This makes it very inconvenient to pass around unless the templates are static strings.
There are generally two ways to construct an environment:
Environment::new
creates an environment preconfigured with sensible defaults. It will contain all built-in filters, tests and globals as well as a callback for auto escaping based on file extension.Environment::empty
creates a completely blank environment.
Implementations
sourceimpl<'source> Environment<'source>
impl<'source> Environment<'source>
sourcepub fn new() -> Environment<'source>
pub fn new() -> Environment<'source>
Creates a new environment with sensible defaults.
This environment does not yet contain any templates but it will have all
the default filters, tests and globals loaded. If you do not want any
default configuration you can use the alternative
empty
method.
sourcepub fn empty() -> Environment<'source>
pub fn empty() -> Environment<'source>
Creates a completely empty environment.
This environment has no filters, no templates, no globals and no default logic for auto escaping configured.
sourcepub fn add_template(
&mut self,
name: &'source str,
source: &'source str
) -> Result<(), Error>
pub fn add_template(
&mut self,
name: &'source str,
source: &'source str
) -> Result<(), Error>
Loads a template from a string.
The name
parameter defines the name of the template which identifies
it. To look up a loaded template use the get_template
method.
Note that there are situations where the interface of this method is too restrictive. For instance the environment itself does not permit any form of sensible dynamic template loading.
sourcepub fn remove_template(&mut self, name: &str)
pub fn remove_template(&mut self, name: &str)
Removes a template by name.
sourcepub fn get_template(&self, name: &str) -> Result<Template<'_>, Error>
pub fn get_template(&self, name: &str) -> Result<Template<'_>, Error>
Fetches a template by name.
This requires that the template has been loaded with
add_template
beforehand. If the template was
not loaded an error of kind TemplateNotFound
is returned.
let mut env = Environment::new();
env.add_template("hello.txt", "Hello {{ name }}!").unwrap();
let tmpl = env.get_template("hello.txt").unwrap();
println!("{}", tmpl.render(context!{ name => "World" }).unwrap());
sourcepub fn render_str<S: Serialize>(
&self,
source: &str,
ctx: S
) -> Result<String, Error>
pub fn render_str<S: Serialize>(
&self,
source: &str,
ctx: S
) -> Result<String, Error>
Parses and renders a template from a string in one go.
In some cases you really only need a template to be rendered once from
a string and returned. The internal name of the template is <string>
.
let env = Environment::new();
let rv = env.render_str("Hello {{ name }}", context! { name => "World" });
println!("{}", rv.unwrap());
sourcepub fn set_auto_escape_callback<F>(&mut self, f: F)where
F: Fn(&str) -> AutoEscape + 'static + Sync + Send,
pub fn set_auto_escape_callback<F>(&mut self, f: F)where
F: Fn(&str) -> AutoEscape + 'static + Sync + Send,
Sets a new function to select the default auto escaping.
This function is invoked when templates are loaded from the environment
to determine the default auto escaping behavior. The function is
invoked with the name of the template and can make an initial auto
escaping decision based on that. The default implementation
(default_auto_escape_callback
)
turn on escaping depending on the file extension.
env.set_auto_escape_callback(|name| {
if matches!(name.rsplit('.').next().unwrap_or(""), "html" | "htm" | "aspx") {
AutoEscape::Html
} else {
AutoEscape::None
}
});
sourcepub fn set_formatter<F>(&mut self, f: F)where
F: Fn(&mut Output<'_>, &State<'_, '_>, &Value) -> Result<(), Error> + 'static + Sync + Send,
pub fn set_formatter<F>(&mut self, f: F)where
F: Fn(&mut Output<'_>, &State<'_, '_>, &Value) -> Result<(), Error> + 'static + Sync + Send,
Sets a different formatter function.
The formatter is invoked to format the given value into the provided
Output
. The default implementation is
escape_formatter
.
When implementing a custom formatter it depends on if auto escaping
should be supported or not. If auto escaping should be supported then
it’s easiest to just wrap the default formatter. The
following example swaps out None
values before rendering for
Undefined
which renders as an empty string instead.
The current value of the auto escape flag can be retrieved directly
from the State
.
use minijinja::escape_formatter;
use minijinja::value::Value;
env.set_formatter(|out, state, value| {
escape_formatter(
out,
state,
if value.is_none() {
&Value::UNDEFINED
} else {
value
},
)
});
sourcepub fn set_debug(&mut self, enabled: bool)
pub fn set_debug(&mut self, enabled: bool)
Enable or disable the debug mode.
When the debug mode is enabled the engine will dump out some of the execution state together with the source information of the executing template when an error is created. The cost of this is relatively high as the data including the template source is cloned.
When this is enabled templates will print debug information with source context when the error is printed.
This requires the debug
feature. This is enabled by default if
debug assertions are enabled and false otherwise.
sourcepub fn compile_expression(
&self,
expr: &'source str
) -> Result<Expression<'_, 'source>, Error>
pub fn compile_expression(
&self,
expr: &'source str
) -> Result<Expression<'_, 'source>, Error>
Compiles an expression.
This lets one compile an expression in the template language and
receive the output. This lets one use the expressions of the language
be used as a minimal scripting language. For more information and an
example see Expression
.
sourcepub fn add_filter<F, Rv, Args>(&mut self, name: &'source str, f: F)where
F: Filter<Rv, Args> + for<'a> Filter<Rv, <Args as FunctionArgs<'a>>::Output>,
Rv: FunctionResult,
Args: for<'a> FunctionArgs<'a>,
pub fn add_filter<F, Rv, Args>(&mut self, name: &'source str, f: F)where
F: Filter<Rv, Args> + for<'a> Filter<Rv, <Args as FunctionArgs<'a>>::Output>,
Rv: FunctionResult,
Args: for<'a> FunctionArgs<'a>,
Adds a new filter function.
Filter functions are functions that can be applied to values in
templates. For details about filters have a look at
Filter
.
sourcepub fn remove_filter(&mut self, name: &str)
pub fn remove_filter(&mut self, name: &str)
Removes a filter by name.
sourcepub fn add_test<F, Rv, Args>(&mut self, name: &'source str, f: F)where
F: Test<Rv, Args> + for<'a> Test<Rv, <Args as FunctionArgs<'a>>::Output>,
Rv: TestResult,
Args: for<'a> FunctionArgs<'a>,
pub fn add_test<F, Rv, Args>(&mut self, name: &'source str, f: F)where
F: Test<Rv, Args> + for<'a> Test<Rv, <Args as FunctionArgs<'a>>::Output>,
Rv: TestResult,
Args: for<'a> FunctionArgs<'a>,
Adds a new test function.
Test functions are similar to filters but perform a check on a value
where the return value is always true or false. For details about tests
have a look at Test
.
sourcepub fn remove_test(&mut self, name: &str)
pub fn remove_test(&mut self, name: &str)
Removes a test by name.
sourcepub fn add_function<F, Rv, Args>(&mut self, name: &'source str, f: F)where
F: Function<Rv, Args> + for<'a> Function<Rv, <Args as FunctionArgs<'a>>::Output>,
Rv: FunctionResult,
Args: for<'a> FunctionArgs<'a>,
pub fn add_function<F, Rv, Args>(&mut self, name: &'source str, f: F)where
F: Function<Rv, Args> + for<'a> Function<Rv, <Args as FunctionArgs<'a>>::Output>,
Rv: FunctionResult,
Args: for<'a> FunctionArgs<'a>,
sourcepub fn add_global(&mut self, name: &'source str, value: Value)
pub fn add_global(&mut self, name: &'source str, value: Value)
Adds a global variable.
sourcepub fn remove_global(&mut self, name: &str)
pub fn remove_global(&mut self, name: &str)
Removes a global function or variable by name.
Trait Implementations
sourceimpl<'source> Clone for Environment<'source>
impl<'source> Clone for Environment<'source>
sourcefn clone(&self) -> Environment<'source>
fn clone(&self) -> Environment<'source>
1.0.0 · sourcefn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more