rocket_dyn_templates::minijinja

Struct 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§

Source§

impl<'source> Environment<'source>

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.

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.

Source

pub fn add_template( &mut self, name: &'source str, source: &'source str, ) -> Result<(), Error>

Loads a template from a string into the environment.

The name parameter defines the name of the template which identifies it. To look up a loaded template use the get_template method.

let mut env = Environment::new();
env.add_template("index.html", "Hello {{ name }}!").unwrap();

Note that there are situations where the interface of this method is too restrictive as you need to hold on to the strings for the lifetime of the environment. This methodl fails if the template has a syntax error. To address this restriction use add_template_owned.

Source

pub fn add_template_owned<N, S>( &mut self, name: N, source: S, ) -> Result<(), Error>
where N: Into<Cow<'source, str>>, S: Into<Cow<'source, str>>,

Adds a template without borrowing.

This lets you place an owned String in the environment rather than the borrowed &str without having to worry about lifetimes.

let mut env = Environment::new();
env.add_template_owned("index.html".to_string(), "Hello {{ name }}!".to_string()).unwrap();

Note: the name is a bit of a misnomer as this API also allows to borrow too as the parameters are actually Cow. This method fails if the template has a syntax error.

Source

pub fn set_loader<F>(&mut self, f: F)
where F: Fn(&str) -> Result<Option<String>, Error> + Send + Sync + 'static,

Register a template loader as source of templates.

When a template loader is registered, the environment gains the ability to dynamically load templates. The loader is invoked with the name of the template. If this template exists Ok(Some(template_source)) has to be returned, otherwise Ok(None). Once a template has been loaded it’s stored on the environment. This means the loader is only invoked once per template name.

For loading templates from the file system, you can use the path_loader function.

§Example
fn create_env() -> Environment<'static> {
    let mut env = Environment::new();
    env.set_loader(|name| {
        if name == "layout.html" {
            Ok(Some("...".into()))
        } else {
            Ok(None)
        }
    });
    env
}
Source

pub fn set_keep_trailing_newline(&mut self, yes: bool)

Preserve the trailing newline when rendering templates.

The default is false, which causes a single newline, if present, to be stripped from the end of the template.

This setting is used whenever a template is loaded into the environment. Changing it at a later point only affects future templates loaded.

Source

pub fn keep_trailing_newline(&self) -> bool

Returns the value of the trailing newline preservation flag.

Source

pub fn set_trim_blocks(&mut self, yes: bool)

Remove the first newline after a block.

If this is set to true then the first newline after a block is removed (block, not variable tag!). Defaults to false.

Source

pub fn trim_blocks(&self) -> bool

Returns the value of the trim blocks flag.

Source

pub fn set_lstrip_blocks(&mut self, yes: bool)

Remove leading spaces and tabs from the start of a line to a block.

If this is set to true then leading spaces and tabs from the start of a line to the block tag are removed.

Source

pub fn lstrip_blocks(&self) -> bool

Returns the value of the lstrip blocks flag.

Source

pub fn remove_template(&mut self, name: &str)

Removes a template by name.

Source

pub fn set_path_join_callback<F>(&mut self, f: F)
where F: for<'s> Fn(&'s str, &'s str) -> Cow<'s, str> + Send + Sync + 'static,

Sets a callback to join template paths.

By default this returns the template path unchanged, but it can be used to implement relative path resolution between templates. The first argument to the callback is the name of the template to be loaded, the second argument is the parent path.

The following example demonstrates how a basic path joining algorithm can be implemented.

env.set_path_join_callback(|name, parent| {
    let mut rv = parent.split('/').collect::<Vec<_>>();
    rv.pop();
    name.split('/').for_each(|segment| match segment {
        "." => {}
        ".." => { rv.pop(); }
        _ => { rv.push(segment); }
    });
    rv.join("/").into()
});
Source

pub fn set_unknown_method_callback<F>(&mut self, f: F)
where F: Fn(&State<'_, '_>, &Value, &str, &[Value]) -> Result<Value, Error> + Sync + Send + 'static,

Sets a callback invoked for unknown methods on objects.

This registers a function with the environment that is invoked when invoking a method on a value results in a UnknownMethod error. In that case the callback is invoked with State, the Value, the name of the method as &str as well as all arguments in a slice.

This for instance implements a .items() method that invokes the |items filter:

use minijinja::value::{ValueKind, from_args};
use minijinja::{Error, ErrorKind};

env.set_unknown_method_callback(|state, value, method, args| {
    if value.kind() == ValueKind::Map && method == "items" {
        let _: () = from_args(args)?;
        state.apply_filter("items", &[value.clone()])
    } else {
        Err(Error::from(ErrorKind::UnknownMethod))
    }
});

This can be used to increase the compatibility with Jinja2 templates that might call Python methods on objects which are not available in minijinja. A range of common Python methods is implemented in minijinja-contrib. For more information see minijinja_contrib::pycompat.

Source

pub fn clear_templates(&mut self)

Removes all stored templates.

This method is mainly useful when combined with a loader as it causes the loader to “reload” templates. By calling this method one can trigger a reload.

Source

pub fn templates(&self) -> impl Iterator<Item = (&str, Template<'_, '_>)>

Returns an iterator over the already loaded templates and their names.

Only templates that are already loaded will be returned.

let mut env = Environment::new();
env.add_template("hello.txt", "Hello {{ name }}!").unwrap();
env.add_template("goodbye.txt", "Goodbye {{ name }}!").unwrap();

for (name, tmpl) in env.templates() {
    println!("{}", tmpl.render(context!{ name => "World" }).unwrap());
}
Source

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. If a loader was added to the engine this can also dynamically load templates.

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());
Source

pub fn template_from_named_str( &self, name: &'source str, source: &'source str, ) -> Result<Template<'_, 'source>, Error>

Loads a template from a string.

In some cases you really only need to work with (eg: render) a template to be rendered once only.

let env = Environment::new();
let tmpl = env.template_from_named_str("template_name", "Hello {{ name }}").unwrap();
let rv = tmpl.render(context! { name => "World" });
println!("{}", rv.unwrap());
Source

pub fn template_from_str( &self, source: &'source str, ) -> Result<Template<'_, 'source>, Error>

Loads a template from a string, with name <string>.

This is a shortcut to template_from_named_str with name set to <string>.

Source

pub fn render_named_str<S>( &self, name: &str, source: &str, ctx: S, ) -> Result<String, Error>
where S: Serialize,

Parses and renders a template from a string in one go with name.

Like render_str, but provide a name for the template to be used instead of the default <string>. This is an alias for template_from_named_str paired with render.

let env = Environment::new();
let rv = env.render_named_str(
    "template_name",
    "Hello {{ name }}",
    context!{ name => "World" }
);
println!("{}", rv.unwrap());

Note on values: The Value type implements Serialize and can be efficiently passed to render. It does not undergo actual serialization.

Source

pub fn render_str<S>(&self, source: &str, ctx: S) -> Result<String, Error>
where S: Serialize,

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>.

This is an alias for template_from_str paired with render.

Note on values: The Value type implements Serialize and can be efficiently passed to render. It does not undergo actual serialization.

Source

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 into 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
    }
});
Source

pub fn set_undefined_behavior(&mut self, behavior: UndefinedBehavior)

Changes the undefined behavior.

This changes the runtime behavior of undefined values in the template engine. For more information see UndefinedBehavior. The default is UndefinedBehavior::Lenient.

Source

pub fn undefined_behavior(&self) -> UndefinedBehavior

Returns the current undefined behavior.

This is particularly useful if a filter function or similar wants to change its behavior with regards to undefined values.

Source

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
        },
    )
});
Source

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.

Source

pub fn debug(&self) -> bool

Returns the current value of the debug flag.

Source

pub fn set_recursion_limit(&mut self, level: usize)

Reconfigures the runtime recursion limit.

This defaults to 500. Raising it above that level requires the stacker feature to be enabled. Otherwise the limit is silently capped at that safe maximum. Note that the maximum is not necessarily safe if the thread uses a lot of stack space already, it’s just a value that was validated once to provide basic protection.

Every operation that requires recursion in MiniJinja increments an internal recursion counter. The actual cost attributed to that recursion depends on the cost of the operation. If statements and for loops for instance only increase the counter by 1, whereas template includes and macros might increase it to 10 or more.

Note on stack growth: even if the stacker feature is enabled it does not mean that in all cases stack can grow to the limits desired. For instance in WASM the maximum limits are additionally enforced by the runtime.

Source

pub fn recursion_limit(&self) -> usize

Returns the current max recursion limit.

Source

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.

Source

pub fn compile_expression_owned<E>( &self, expr: E, ) -> Result<Expression<'_, 'source>, Error>
where E: Into<Cow<'source, str>>,

Compiles an expression without capturing the lifetime.

This works exactly like compile_expression but lets you pass an owned string without capturing the lifetime.

Source

pub fn add_filter<N, F, Rv, Args>(&mut self, name: N, f: F)
where N: Into<Cow<'source, str>>, 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.

Source

pub fn remove_filter(&mut self, name: &str)

Removes a filter by name.

Source

pub fn add_test<N, F, Rv, Args>(&mut self, name: N, f: F)
where N: Into<Cow<'source, str>>, 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.

Source

pub fn remove_test(&mut self, name: &str)

Removes a test by name.

Source

pub fn add_function<N, F, Rv, Args>(&mut self, name: N, f: F)
where N: Into<Cow<'source, str>>, F: Function<Rv, Args> + for<'a> Function<Rv, <Args as FunctionArgs<'a>>::Output>, Rv: FunctionResult, Args: for<'a> FunctionArgs<'a>,

Adds a new global function.

For details about functions have a look at functions. Note that functions and other global variables share the same namespace. For more details about functions have a look at Function.

Source

pub fn add_global<N, V>(&mut self, name: N, value: V)
where N: Into<Cow<'source, str>>, V: Into<Value>,

Adds a global variable.

Source

pub fn remove_global(&mut self, name: &str)

Removes a global function or variable by name.

Source

pub fn empty_state(&self) -> State<'_, '_>

Returns an empty State for testing purposes and similar.

Trait Implementations§

Source§

impl<'source> Clone for Environment<'source>

Source§

fn clone(&self) -> Environment<'source>

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<'source> Debug for Environment<'source>

Source§

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

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

impl<'source> Default for Environment<'source>

Source§

fn default() -> Environment<'source>

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

Auto Trait Implementations§

§

impl<'source> !Freeze for Environment<'source>

§

impl<'source> !RefUnwindSafe for Environment<'source>

§

impl<'source> Send for Environment<'source>

§

impl<'source> Sync for Environment<'source>

§

impl<'source> Unpin for Environment<'source>

§

impl<'source> !UnwindSafe for Environment<'source>

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T> AsTaggedExplicit<'a> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self>

Source§

impl<'a, T> AsTaggedImplicit<'a> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self>

Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

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

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.

§

impl<T> IntoCollection<T> for T

§

fn into_collection<A>(self) -> SmallVec<A>
where A: Array<Item = T>,

Converts self into a collection.
§

fn mapped<U, F, A>(self, f: F) -> SmallVec<A>
where F: FnMut(T) -> U, A: Array<Item = U>,

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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 more
Source§

impl<T> Paint for T
where T: ?Sized,

Source§

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 primary(&self) -> Painted<&T>

Returns self with the fg() set to Color::Primary.

§Example
println!("{}", value.primary());
Source§

fn fixed(&self, color: u8) -> Painted<&T>

Returns self with the fg() set to Color::Fixed.

§Example
println!("{}", value.fixed(color));
Source§

fn rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the fg() set to Color::Rgb.

§Example
println!("{}", value.rgb(r, g, b));
Source§

fn black(&self) -> Painted<&T>

Returns self with the fg() set to Color::Black.

§Example
println!("{}", value.black());
Source§

fn red(&self) -> Painted<&T>

Returns self with the fg() set to Color::Red.

§Example
println!("{}", value.red());
Source§

fn green(&self) -> Painted<&T>

Returns self with the fg() set to Color::Green.

§Example
println!("{}", value.green());
Source§

fn yellow(&self) -> Painted<&T>

Returns self with the fg() set to Color::Yellow.

§Example
println!("{}", value.yellow());
Source§

fn blue(&self) -> Painted<&T>

Returns self with the fg() set to Color::Blue.

§Example
println!("{}", value.blue());
Source§

fn magenta(&self) -> Painted<&T>

Returns self with the fg() set to Color::Magenta.

§Example
println!("{}", value.magenta());
Source§

fn cyan(&self) -> Painted<&T>

Returns self with the fg() set to Color::Cyan.

§Example
println!("{}", value.cyan());
Source§

fn white(&self) -> Painted<&T>

Returns self with the fg() set to Color::White.

§Example
println!("{}", value.white());
Source§

fn bright_black(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightBlack.

§Example
println!("{}", value.bright_black());
Source§

fn bright_red(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightRed.

§Example
println!("{}", value.bright_red());
Source§

fn bright_green(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightGreen.

§Example
println!("{}", value.bright_green());
Source§

fn bright_yellow(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightYellow.

§Example
println!("{}", value.bright_yellow());
Source§

fn bright_blue(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightBlue.

§Example
println!("{}", value.bright_blue());
Source§

fn bright_magenta(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightMagenta.

§Example
println!("{}", value.bright_magenta());
Source§

fn bright_cyan(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightCyan.

§Example
println!("{}", value.bright_cyan());
Source§

fn bright_white(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightWhite.

§Example
println!("{}", value.bright_white());
Source§

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>

Returns self with the bg() set to Color::Primary.

§Example
println!("{}", value.on_primary());
Source§

fn on_fixed(&self, color: u8) -> Painted<&T>

Returns self with the bg() set to Color::Fixed.

§Example
println!("{}", value.on_fixed(color));
Source§

fn on_rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the bg() set to Color::Rgb.

§Example
println!("{}", value.on_rgb(r, g, b));
Source§

fn on_black(&self) -> Painted<&T>

Returns self with the bg() set to Color::Black.

§Example
println!("{}", value.on_black());
Source§

fn on_red(&self) -> Painted<&T>

Returns self with the bg() set to Color::Red.

§Example
println!("{}", value.on_red());
Source§

fn on_green(&self) -> Painted<&T>

Returns self with the bg() set to Color::Green.

§Example
println!("{}", value.on_green());
Source§

fn on_yellow(&self) -> Painted<&T>

Returns self with the bg() set to Color::Yellow.

§Example
println!("{}", value.on_yellow());
Source§

fn on_blue(&self) -> Painted<&T>

Returns self with the bg() set to Color::Blue.

§Example
println!("{}", value.on_blue());
Source§

fn on_magenta(&self) -> Painted<&T>

Returns self with the bg() set to Color::Magenta.

§Example
println!("{}", value.on_magenta());
Source§

fn on_cyan(&self) -> Painted<&T>

Returns self with the bg() set to Color::Cyan.

§Example
println!("{}", value.on_cyan());
Source§

fn on_white(&self) -> Painted<&T>

Returns self with the bg() set to Color::White.

§Example
println!("{}", value.on_white());
Source§

fn on_bright_black(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightBlack.

§Example
println!("{}", value.on_bright_black());
Source§

fn on_bright_red(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightRed.

§Example
println!("{}", value.on_bright_red());
Source§

fn on_bright_green(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightGreen.

§Example
println!("{}", value.on_bright_green());
Source§

fn on_bright_yellow(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightYellow.

§Example
println!("{}", value.on_bright_yellow());
Source§

fn on_bright_blue(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightBlue.

§Example
println!("{}", value.on_bright_blue());
Source§

fn on_bright_magenta(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightMagenta.

§Example
println!("{}", value.on_bright_magenta());
Source§

fn on_bright_cyan(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightCyan.

§Example
println!("{}", value.on_bright_cyan());
Source§

fn on_bright_white(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightWhite.

§Example
println!("{}", value.on_bright_white());
Source§

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 bold(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Bold.

§Example
println!("{}", value.bold());
Source§

fn dim(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Dim.

§Example
println!("{}", value.dim());
Source§

fn italic(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Italic.

§Example
println!("{}", value.italic());
Source§

fn underline(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Underline.

§Example
println!("{}", value.underline());

Returns self with the attr() set to Attribute::Blink.

§Example
println!("{}", value.blink());

Returns self with the attr() set to Attribute::RapidBlink.

§Example
println!("{}", value.rapid_blink());
Source§

fn invert(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Invert.

§Example
println!("{}", value.invert());
Source§

fn conceal(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Conceal.

§Example
println!("{}", value.conceal());
Source§

fn strike(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Strike.

§Example
println!("{}", value.strike());
Source§

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 mask(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Mask.

§Example
println!("{}", value.mask());
Source§

fn wrap(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Wrap.

§Example
println!("{}", value.wrap());
Source§

fn linger(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Linger.

§Example
println!("{}", value.linger());
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.

Returns self with the quirk() set to Quirk::Clear.

§Example
println!("{}", value.clear());
Source§

fn resetting(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Resetting.

§Example
println!("{}", value.resetting());
Source§

fn bright(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Bright.

§Example
println!("{}", value.bright());
Source§

fn on_bright(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::OnBright.

§Example
println!("{}", value.on_bright());
Source§

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);
Source§

fn new(self) -> Painted<Self>
where Self: Sized,

Create a new Painted with a default Style. Read more
Source§

fn paint<S>(&self, style: S) -> Painted<&Self>
where S: Into<Style>,

Apply a style wholesale to self. Any previous style is replaced. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize = _

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

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 T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
Source§

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

Source§

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

The type returned in the event of a conversion error.
Source§

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

Performs the conversion.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more