pub struct Template<'env, 'source>where
'env: 'source,{ /* private fields */ }Expand description
Represents a handle to a template.
Templates are stored in the Environment as bytecode instructions. With the
Environment::get_template method that is looked up and returned in form of
this handle. Such a template can be cheaply copied as it only holds references.
To render the render method can be used.
Implementations§
Source§impl<'env, 'source> Template<'env, 'source>
impl<'env, 'source> Template<'env, 'source>
Sourcepub fn render<V>(&self, ctx: V) -> Result<String, Error>
pub fn render<V>(&self, ctx: V) -> Result<String, Error>
Renders the template into a string.
The provided value is used as the initial context for the template. It
can be any object that implements Into<Value>. The
context! macro can be used to create an ad-hoc context.
Serde values can be passed explicitly with the
minijinja::value::Serde wrapper.
For very large contexts and to avoid the overhead of serialization of
potentially unused values, you might consider using a dynamic
Object as value. For more
information see Map as Context.
let tmpl = env.get_template("hello").unwrap();
println!("{}", tmpl.render(context!(name => "John")).unwrap());To render a single block use render_captured
in combination with State::render_block.
Sourcepub fn render_with_spans<V>(
&self,
ctx: V,
) -> Result<(String, Vec<OutputSpan>), Error>
pub fn render_with_spans<V>( &self, ctx: V, ) -> Result<(String, Vec<OutputSpan>), Error>
Like render but also returns the spans of the
template source that produced the output.
This is useful when the rendered output is processed further (for
instance parsed as markup) and problems found there should be reported
at the template location that produced them. The returned
OutputSpans are ordered by their position in the output and
do not overlap. Empty output does not produce spans.
Output that is captured before it is written (the output of macros,
{% filter %} and {% call %} blocks) is attributed to the expression
that writes the captured value. Output of included templates and
blocks is attributed to the template that contains the source.
This requires the debug feature but does not require debug mode to be
enabled on the environment.
let env = Environment::new();
let tmpl = env.template_from_str("Hello {{ name }}!").unwrap();
let (output, spans) = tmpl.render_with_spans(context!(name => "John")).unwrap();
assert_eq!(output, "Hello John!");
let span = &spans[1];
assert_eq!(&output[span.output_range()], "John");
assert_eq!(&tmpl.source()[span.source_range()], "name");
assert_eq!(span.kind(), OutputSpanKind::Expression);
assert_eq!(span.line(), 1);Sourcepub fn render_captured<V>(&self, ctx: V) -> Result<Captured<'source>, Error>
pub fn render_captured<V>(&self, ctx: V) -> Result<Captured<'source>, Error>
Like render but also returns the evaluated State
while keeping the template alive with the returned state.
This is primarily useful when working with temporary template handles,
as the resulting State can continue to be used through the returned
wrapper.
let env = Environment::new();
let rendered = env
.template_from_str("{% set x = 42 %}")
.unwrap()
.render_captured(())
.unwrap();
assert_eq!(rendered.output(), "");
assert_eq!(rendered.state().lookup("x"), Some(Value::from(42)));Sourcepub fn render_captured_to<V, W>(
&self,
ctx: V,
w: W,
) -> Result<Captured<'source>, Error>
pub fn render_captured_to<V, W>( &self, ctx: V, w: W, ) -> Result<Captured<'source>, Error>
Like render but writes to an io::Write and keeps
the template alive with the returned state.
This is useful when working with temporary template handles and
the state needs to be inspected afterwards. The output
of the returned Captured will be an empty string since the
output was written to the provided writer.
let env = Environment::new();
let mut buf = Vec::new();
let captured = env
.template_from_str("{% set x = 42 %}Hello!")
.unwrap()
.render_captured_to((), &mut buf)
.unwrap();
assert_eq!(std::str::from_utf8(&buf).unwrap(), "Hello!");
assert_eq!(captured.output(), "");Sourcepub fn undeclared_variables(&self, nested: bool) -> HashSet<String>
pub fn undeclared_variables(&self, nested: bool) -> HashSet<String>
Returns a set of all undeclared variables in the template.
This returns a set of all variables that might be looked up
at runtime by the template. Since this runs a static
analysis, the actual control flow is not considered. This
also cannot take into account what happens due to includes,
imports or extending. If nested is set to true, then also
nested trivial attribute lookups are considered and returned.
let mut env = Environment::new();
env.add_template("x", "{% set x = foo %}{{ x }}{{ bar.baz }}").unwrap();
let tmpl = env.get_template("x").unwrap();
let undeclared = tmpl.undeclared_variables(false);
// returns ["foo", "bar"]
let undeclared = tmpl.undeclared_variables(true);
// returns ["foo", "bar.baz"]Note that this does not special case global variables. This means
that for instance a template that uses namespace() will return
namespace in the return value.
Trait Implementations§
Auto Trait Implementations§
impl<'env, 'source> !RefUnwindSafe for Template<'env, 'source>
impl<'env, 'source> !UnwindSafe for Template<'env, 'source>
impl<'env, 'source> Forget for Template<'env, 'source>
impl<'env, 'source> Freeze for Template<'env, 'source>
impl<'env, 'source> Move for Template<'env, 'source>
impl<'env, 'source> Send for Template<'env, 'source>
impl<'env, 'source> Sync for Template<'env, 'source>
impl<'env, 'source> Unpin for Template<'env, 'source>
impl<'env, 'source> UnsafeUnpin for Template<'env, 'source>
Blanket Implementations§
Source§impl<T> AsAny for Twhere
T: Any,
impl<T> AsAny for Twhere
T: Any,
fn as_any_ref(&self) -> &(dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Paint for Twhere
T: ?Sized,
impl<T> Paint for Twhere
T: ?Sized,
Source§fn fg(&self, value: Color) -> Painted<&T>
fn fg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the foreground set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like red() and
green(), which have the same functionality but are
pithier.
§Example
Set foreground color to white using fg():
use yansi::{Paint, Color};
painted.fg(Color::White);Set foreground color to white using white().
use yansi::Paint;
painted.white();Source§fn bright_black(&self) -> Painted<&T>
fn bright_black(&self) -> Painted<&T>
Source§fn bright_red(&self) -> Painted<&T>
fn bright_red(&self) -> Painted<&T>
Source§fn bright_green(&self) -> Painted<&T>
fn bright_green(&self) -> Painted<&T>
Source§fn bright_yellow(&self) -> Painted<&T>
fn bright_yellow(&self) -> Painted<&T>
Source§fn bright_blue(&self) -> Painted<&T>
fn bright_blue(&self) -> Painted<&T>
Source§fn bright_magenta(&self) -> Painted<&T>
fn bright_magenta(&self) -> Painted<&T>
Source§fn bright_cyan(&self) -> Painted<&T>
fn bright_cyan(&self) -> Painted<&T>
Source§fn bright_white(&self) -> Painted<&T>
fn bright_white(&self) -> Painted<&T>
Source§fn bg(&self, value: Color) -> Painted<&T>
fn bg(&self, value: Color) -> Painted<&T>
Returns a styled value derived from self with the background set to
value.
This method should be used rarely. Instead, prefer to use color-specific
builder methods like on_red() and
on_green(), which have the same functionality but
are pithier.
§Example
Set background color to red using fg():
use yansi::{Paint, Color};
painted.bg(Color::Red);Set background color to red using on_red().
use yansi::Paint;
painted.on_red();Source§fn on_primary(&self) -> Painted<&T>
fn on_primary(&self) -> Painted<&T>
Source§fn on_magenta(&self) -> Painted<&T>
fn on_magenta(&self) -> Painted<&T>
Source§fn on_bright_black(&self) -> Painted<&T>
fn on_bright_black(&self) -> Painted<&T>
Source§fn on_bright_red(&self) -> Painted<&T>
fn on_bright_red(&self) -> Painted<&T>
Source§fn on_bright_green(&self) -> Painted<&T>
fn on_bright_green(&self) -> Painted<&T>
Source§fn on_bright_yellow(&self) -> Painted<&T>
fn on_bright_yellow(&self) -> Painted<&T>
Source§fn on_bright_blue(&self) -> Painted<&T>
fn on_bright_blue(&self) -> Painted<&T>
Source§fn on_bright_magenta(&self) -> Painted<&T>
fn on_bright_magenta(&self) -> Painted<&T>
Source§fn on_bright_cyan(&self) -> Painted<&T>
fn on_bright_cyan(&self) -> Painted<&T>
Source§fn on_bright_white(&self) -> Painted<&T>
fn on_bright_white(&self) -> Painted<&T>
Source§fn attr(&self, value: Attribute) -> Painted<&T>
fn attr(&self, value: Attribute) -> Painted<&T>
Enables the styling Attribute value.
This method should be used rarely. Instead, prefer to use
attribute-specific builder methods like bold() and
underline(), which have the same functionality
but are pithier.
§Example
Make text bold using attr():
use yansi::{Paint, Attribute};
painted.attr(Attribute::Bold);Make text bold using using bold().
use yansi::Paint;
painted.bold();Source§fn rapid_blink(&self) -> Painted<&T>
fn rapid_blink(&self) -> Painted<&T>
Source§fn quirk(&self, value: Quirk) -> Painted<&T>
fn quirk(&self, value: Quirk) -> Painted<&T>
Enables the yansi Quirk value.
This method should be used rarely. Instead, prefer to use quirk-specific
builder methods like mask() and
wrap(), which have the same functionality but are
pithier.
§Example
Enable wrapping using .quirk():
use yansi::{Paint, Quirk};
painted.quirk(Quirk::Wrap);Enable wrapping using wrap().
use yansi::Paint;
painted.wrap();Source§fn clear(&self) -> Painted<&T>
👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
fn clear(&self) -> Painted<&T>
renamed to resetting() due to conflicts with Vec::clear().
The clear() method will be removed in a future release.
Source§fn whenever(&self, value: Condition) -> Painted<&T>
fn whenever(&self, value: Condition) -> Painted<&T>
Conditionally enable styling based on whether the Condition value
applies. Replaces any previous condition.
See the crate level docs for more details.
§Example
Enable styling painted only when both stdout and stderr are TTYs:
use yansi::{Paint, Condition};
painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);