pub struct Tera { /* private fields */ }Expand description
Main point of interaction in this library.
The Tera struct is the primary interface for working with the Tera template engine. It contains parsed templates, registered filters (which can filter
data), functions, and testers. It also contains some configuration options, such as a list of
suffixes for files that have autoescaping turned on.
It is responsible for:
- Loading and managing templates from files or strings
- Parsing templates and checking for syntax errors
- Maintaining a cache of compiled templates for efficient rendering
- Providing an interface for rendering templates with given contexts
- Managing template inheritance and includes
- Handling custom filters and functions
- Overriding settings, such as autoescape rules
§Example
Basic usage:
use tera::Tera;
let mut tera = Tera::default();
tera.add_raw_template("hello", "Hello, {{ name }}!").unwrap();
// Prepare the context with some data
let mut context = tera::Context::new();
context.insert("name", "World");
// Render the template with the given context
let rendered = tera.render("hello", &context).unwrap();
assert_eq!(rendered, "Hello, World!");Implementations§
Source§impl Tera
impl Tera
Sourcepub fn autoescape_on(
&mut self,
suffixes: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
)
pub fn autoescape_on( &mut self, suffixes: impl IntoIterator<Item = impl Into<Cow<'static, str>>>, )
Select which suffix(es) to automatically do HTML escaping on.
By default, autoescaping is performed on .html, .htm and .xml template files. Only
call this function if you wish to change the defaults.
§Examples
Basic usage:
let mut tera = Tera::default();
// escape only files ending with `.php.html`
tera.autoescape_on([".php.html"]);
// disable autoescaping completely
tera.autoescape_on(Vec::<&str>::new());Sourcepub fn set_delimiters(&mut self, delimiters: Delimiters) -> Result<(), Error>
pub fn set_delimiters(&mut self, delimiters: Delimiters) -> Result<(), Error>
Set custom delimiters for template syntax.
This must be called before adding any templates. Returns an error if any delimiter is empty, if start delimiters conflict or if there are already templates added to the Tera instance.
§Example
use tera::{Tera, Delimiters};
let mut tera = Tera::new();
tera.set_delimiters(Delimiters {
block_start: "<%".into(),
block_end: "%>".into(),
variable_start: "<<".into(),
variable_end: ">>".into(),
comment_start: "<#".into(),
comment_end: "#>".into(),
}).unwrap();
tera.add_raw_template("example", "<< name >>").unwrap();Sourcepub fn set_escape_fn(
&mut self,
function: fn(&str, &mut dyn Write) -> Result<(), Error>,
)
pub fn set_escape_fn( &mut self, function: fn(&str, &mut dyn Write) -> Result<(), Error>, )
Set user-defined function that is used to escape content.
Often times, arbitrary data needs to be injected into a template without allowing injection attacks. For this reason, typically escaping is performed on all input. By default, the escaping function will produce HTML escapes, but it can be overridden to produce escapes more appropriate to the language being used.
Inside templates, escaping can be turned off for specific content using the safe filter.
For example, the string {{ data }} inside a template will escape data, while {{ data | safe }} will not.
§Examples
Basic usage:
// Create new Tera instance
let mut tera = Tera::default();
// Override escape function to escape the letter A, why not
tera.set_escape_fn(|input: &str, output: &mut dyn Write| {
for byte in input.bytes() {
match byte {
b'a' => output.write_all(b"?")?,
_ => output.write_all(&[byte])?,
}
}
Ok(())
});
// Create template and enable autoescape
tera.add_raw_template("hello.js", "const data = \"{{ content }}\";").unwrap();
tera.autoescape_on(vec!["js"]);
// Create context with some data
let mut context = Context::new();
context.insert("content", &r#"Hello tera"#);
// Render template
let result = tera.render("hello.js", &context).unwrap();
assert_eq!(result, r#"const data = "Hello ter?";"#);Sourcepub fn reset_escape_fn(&mut self)
pub fn reset_escape_fn(&mut self)
Reset escape function to default escape_html().
Sourcepub fn register_filter<Func, Arg, Res>(
&mut self,
name: impl Into<Cow<'static, str>>,
filter: Func,
)where
Func: Filter<Arg, Res> + for<'a> Filter<<Arg as ArgFromValue<'a>>::Output, Res>,
Arg: for<'a> ArgFromValue<'a>,
Res: FunctionResult,
pub fn register_filter<Func, Arg, Res>(
&mut self,
name: impl Into<Cow<'static, str>>,
filter: Func,
)where
Func: Filter<Arg, Res> + for<'a> Filter<<Arg as ArgFromValue<'a>>::Output, Res>,
Arg: for<'a> ArgFromValue<'a>,
Res: FunctionResult,
Register a filter with Tera.
If a filter with that name already exists, it will be overwritten. If your filter is returning a String, make sure you check crate::StringInput to handle string safety correctly if relevant.
let mut tera = Tera::default();
tera.register_filter("double", |x: i64, _: Kwargs, _: &State| x * 2);Sourcepub fn register_test<Func, Arg, Res>(
&mut self,
name: impl Into<Cow<'static, str>>,
test: Func,
)where
Func: Test<Arg, Res> + for<'a> Test<<Arg as ArgFromValue<'a>>::Output, Res>,
Arg: for<'a> ArgFromValue<'a>,
Res: TestResult,
pub fn register_test<Func, Arg, Res>(
&mut self,
name: impl Into<Cow<'static, str>>,
test: Func,
)where
Func: Test<Arg, Res> + for<'a> Test<<Arg as ArgFromValue<'a>>::Output, Res>,
Arg: for<'a> ArgFromValue<'a>,
Res: TestResult,
Register a test with Tera.
If a test with that name already exists, it will be overwritten
let mut tera = Tera::default();
tera.register_test("odd", |x: i64, _: Kwargs, _: &State| x % 2 != 0);Sourcepub fn register_function<Func, Res>(
&mut self,
name: impl Into<Cow<'static, str>>,
func: Func,
)where
Func: Function<Res>,
Res: FunctionResult,
pub fn register_function<Func, Res>(
&mut self,
name: impl Into<Cow<'static, str>>,
func: Func,
)where
Func: Function<Res>,
Res: FunctionResult,
Register a function with Tera.
If a function with that name already exists, it will be overwritten
Sourcepub fn register_from(&mut self, other: &Tera)
pub fn register_from(&mut self, other: &Tera)
Register filters, tests, and functions from another Tera instance.
If a filter/test/function with the same name already exists in this instance, it will not be overwritten.
Sourcepub fn get_template_variables(
&self,
template_name: &str,
) -> Result<HashSet<&str>, Error>
pub fn get_template_variables( &self, template_name: &str, ) -> Result<HashSet<&str>, Error>
Does a best-effort to find the top level variables that might be needed to be provided to render the template.
This doesn’t do a full analysis and just reports all top level variables that were found. It doesn’t care about if statements etc.
Sourcepub fn get_component_definition(&self, name: &str) -> Option<ComponentInfo>
pub fn get_component_definition(&self, name: &str) -> Option<ComponentInfo>
Returns information about a registered component definition.
Returns None if no component with the given name is found.
§Examples
let mut tera = Tera::default();
tera.add_raw_template(
"components.html",
r#"{% component Button(label: String, variant="primary") %}<button>{{ label }}</button>{% endcomponent Button %}"#,
).unwrap();
let info = tera.get_component_definition("Button").unwrap();
assert_eq!(info.name(), "Button");
assert_eq!(info.args().len(), 2);Sourcepub fn contains_component(&self, component_name: &str) -> bool
pub fn contains_component(&self, component_name: &str) -> bool
Lookups a component by name, returning whether it’s found or not
Returns false if no component with the given name is found.
§Examples
let mut tera = Tera::default();
tera.add_raw_template(
"components.html",
r#"{% component Button(label: String, variant="primary") %}<button>{{ label }}</button>{% endcomponent Button %}"#,
).unwrap();
assert!(tera.contains_component("Button"));Sourcepub fn get_component_names(&self) -> impl Iterator<Item = &str>
pub fn get_component_names(&self) -> impl Iterator<Item = &str>
Returns an iterator over the names of all registered components in an unspecified order.
§Example
use tera::Tera;
let mut tera = Tera::default();
tera.add_raw_template("foo", "{% component hello(name) %}{{ name }}{% endcomponent %}");
let names: Vec<_> = tera.get_component_names().collect();
assert_eq!(names.len(), 1);
assert!(names.contains(&"hello"));Sourcepub fn add_raw_template(
&mut self,
name: &str,
content: &str,
) -> Result<(), Error>
pub fn add_raw_template( &mut self, name: &str, content: &str, ) -> Result<(), Error>
Add a single template to the Tera instance.
This will error if there are errors in the inheritance, such as adding a child template without the parent one.
§Bulk loading
If you want to add several templates, use
add_raw_templates().
§Examples
Basic usage:
let mut tera = Tera::default();
tera.add_raw_template("new.html", "Blabla").unwrap();Sourcepub fn add_raw_templates<I, N, C>(&mut self, templates: I) -> Result<(), Error>
pub fn add_raw_templates<I, N, C>(&mut self, templates: I) -> Result<(), Error>
Add all the templates given to the Tera instance
This will error if there are errors in the inheritance, such as adding a child template without the parent one.
let mut tera = Tera::default();
tera.add_raw_templates(vec![
("new.html", "blabla"),
("new2.html", "hello"),
]).unwrap();Sourcepub fn add_template_file<P>(
&mut self,
path: P,
name: Option<&str>,
) -> Result<(), Error>
pub fn add_template_file<P>( &mut self, path: P, name: Option<&str>, ) -> Result<(), Error>
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
let mut tera = Tera::default();
// Rename template with custom name
tera.add_template_file("path/to/template.html", Some("template.html")).unwrap();
// Use path as name
tera.add_template_file("path/to/other.html", None).unwrap();Sourcepub fn add_template_files<I, P, N>(&mut self, files: I) -> Result<(), Error>
pub fn add_template_files<I, P, N>(&mut self, files: I) -> Result<(), Error>
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.
let mut tera = Tera::default();
tera.add_template_files(vec![
("./path/to/template.tera", None), // this template will have the value of path1 as name
("./path/to/other.tera", Some("hey")), // this template will have `hey` as name
]);Sourcepub fn set_fallback_prefixes(
&mut self,
prefixes: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
) -> Result<(), Error>
pub fn set_fallback_prefixes( &mut self, prefixes: impl IntoIterator<Item = impl Into<Cow<'static, str>>>, ) -> Result<(), Error>
Set fallback prefixes to try when a template is not found by exact name. This needs to be called before adding templates, it will error otherwise.
When a template is requested (via render, extends, or include) and the exact name is not found, these prefixes are tried in order. The first prefix that produces a match is used.
Prefixes should include any path separator (e.g., "themes/cool/" not "themes/cool").
§Example
let mut tera = Tera::default();
// Templates in "themes/cool/" can be referenced without the prefix
tera.set_fallback_prefixes(["themes/cool/"]).unwrap();Sourcepub fn contains_template(&self, template_name: &str) -> bool
pub fn contains_template(&self, template_name: &str) -> bool
Lookups a template by name, resolving fallback prefixes if needed, returning whether it’s found or not
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"));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 no context, simply pass a Context::new() 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 global_context(&mut self) -> &mut Context
pub fn global_context(&mut self) -> &mut Context
Returns the global context, allowing modifications to it
The global context is automatically included into every template, which is useful for sharing common data.
The global context is not passed if you call render_component but it is available there
for implicit parameter lookup: the components must declare the implicit parameters.
let mut tera = Tera::new();
tera.global_context().insert("name", "John Doe");
let content = tera
.render_str("Hello, {{ name }}!", &Context::new(), false)
.unwrap();
assert_eq!(content, "Hello, John Doe!".to_string());
let content2 = tera
.render_str(
"UserID: {{ id }}, Username: {{ name }}",
&context! { id => &7489 },
false,
)
.unwrap();
assert_eq!(content2, "UserID: 7489, Username: John Doe");Sourcepub fn render_str(
&self,
input: &str,
context: &Context,
autoescape: bool,
) -> Result<String, Error>
pub fn render_str( &self, input: &str, context: &Context, autoescape: bool, ) -> Result<String, Error>
Renders a one-off template (for example a template coming from a user input)
given a Context and using this Tera instance’s filters, tests, functions and components.
The only limitation is that it cannot use {% extends %} and therefore blocks.
Any errors will mention the __tera_one_off template: this is the name
given to the template by Tera.
let tera = Tera::new();
let result = tera.render_str(
"Hello {{ name }}!",
&context! { name => "world" },
false,
).unwrap();
assert_eq!(result, "Hello world!");Sourcepub fn render_str_to(
&self,
input: &str,
context: &Context,
autoescape: bool,
write: impl Write,
) -> Result<(), Error>
pub fn render_str_to( &self, input: &str, context: &Context, autoescape: bool, write: impl Write, ) -> Result<(), Error>
Renders a one-off template to a writer.
Same as render_str but writes to a Write implementor.
Sourcepub fn one_off(
input: &str,
context: &Context,
autoescape: bool,
) -> Result<String, Error>
pub fn one_off( input: &str, context: &Context, autoescape: bool, ) -> Result<String, Error>
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 renders 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");
let result = Tera::one_off("{{ greeting }} world", &context, true).unwrap();
assert_eq!(result, "hello world");Sourcepub fn render_component(
&self,
component_name: &str,
context: &Context,
body: Option<&str>,
autoescape: bool,
) -> Result<String, Error>
pub fn render_component( &self, component_name: &str, context: &Context, body: Option<&str>, autoescape: bool, ) -> Result<String, Error>
Renders a component by name with the given context and optional body content.
The context should contain the component’s arguments as key-value pairs. Unknown arguments
will error.
If the component has a rest parameter, all the additional values will be added to it.
If the component needs implicit parameters, use render_component_with_implicits.
§Examples
let mut tera = Tera::default();
tera.add_raw_template(
"components.html",
r#"{% component Button(label) %}<button>{{ label }}</button>{% endcomponent Button %}
{% component Card(title) %}<div><h1>{{ title }}</h1>{{ body }}</div>{% endcomponent Card %}"#,
).unwrap();
// Render a component with arguments
let html = tera.render_component(
"Button",
&context! { label => "Click me" },
None,
true,
).unwrap();
assert_eq!(html, "<button>Click me</button>");
// Render a component with body content
let html = tera.render_component(
"Card",
&context! { title => "My Card" },
Some("<p>Card content here</p>"),
true,
).unwrap();
assert_eq!(html, "<div><h1>My Card</h1><p>Card content here</p></div>");Sourcepub fn render_component_to(
&self,
component_name: &str,
context: &Context,
body: Option<&str>,
autoescape: bool,
write: impl Write,
) -> Result<(), Error>
pub fn render_component_to( &self, component_name: &str, context: &Context, body: Option<&str>, autoescape: bool, write: impl Write, ) -> Result<(), Error>
Renders a component by name to something that implements Write.
Same as render_component but writes to a Write implementor
instead of returning a String.
§Examples
let mut tera = Tera::default();
tera.add_raw_template(
"components.html",
r#"{% component Button(label) %}<button>{{ label }}</button>{% endcomponent Button %}"#,
).unwrap();
let mut buffer = Vec::new();
tera.render_component_to(
"Button",
&context! { label => "Click me" },
None,
true,
&mut buffer,
).unwrap();
assert_eq!(buffer, b"<button>Click me</button>");Sourcepub fn render_component_with_implicits(
&self,
component_name: &str,
args: &Context,
implicits: &Context,
body: Option<&str>,
autoescape: bool,
) -> Result<String, Error>
pub fn render_component_with_implicits( &self, component_name: &str, args: &Context, implicits: &Context, body: Option<&str>, autoescape: bool, ) -> Result<String, Error>
Renders a component by name with the given context and optional body content.
The context should contain the component’s arguments as key-value pairs. Unknown arguments will error. If the component has a rest parameter, all the additional values will be added to it. If the component (or a children) depends on implicit parameters, you can pass it as a separate context in this function.
§Examples
let mut tera = Tera::default();
tera.add_raw_template(
"components.html",
r#"{% component Button(label, @lang) %}<button>{{ label }}-{{lang}}</button>{% endcomponent Button %}
{% component Card(title) %}<div><h1>{{ title }}</h1>{{ body }}</div>{% endcomponent Card %}"#,
).unwrap();
// Render a component with arguments
let html = tera.render_component_with_implicits(
"Button",
&context! { label => "Click me" },
&context! { lang => "fr" },
None,
true,
).unwrap();
assert_eq!(html, "<button>Click me-fr</button>");
// Render a component with body content
let html = tera.render_component_with_implicits(
"Card",
&context! { title => "My Card" },
&context! { },
Some("<p>Card content here</p>"),
true,
).unwrap();
assert_eq!(html, "<div><h1>My Card</h1><p>Card content here</p></div>");Sourcepub fn render_component_with_implicits_to(
&self,
component_name: &str,
args: &Context,
implicits: &Context,
body: Option<&str>,
autoescape: bool,
write: impl Write,
) -> Result<(), Error>
pub fn render_component_with_implicits_to( &self, component_name: &str, args: &Context, implicits: &Context, body: Option<&str>, autoescape: bool, write: impl Write, ) -> Result<(), Error>
Renders a component by name to something that implements Write.
Same as render_component_with_implicits but writes to a Write implementor
instead of returning a String.
§Examples
let mut tera = Tera::default();
tera.add_raw_template(
"components.html",
r#"{% component Button(label, @lang) %}<button>{{ label }}-{{lang}}</button>{% endcomponent Button %}"#,
).unwrap();
let mut buffer = Vec::new();
tera.render_component_with_implicits_to(
"Button",
&context! { label => "Click me" },
&context! { lang => "fr" },
None,
true,
&mut buffer,
).unwrap();
assert_eq!(buffer, b"<button>Click me-fr</button>");Sourcepub fn render_block(
&self,
template_name: &str,
block_name: &str,
context: &Context,
) -> Result<String, Error>
pub fn render_block( &self, template_name: &str, block_name: &str, context: &Context, ) -> Result<String, Error>
Renders a block by name with the given context.
§Examples
// Create new tera instance with demo template
let mut tera = Tera::default();
tera.add_raw_template("hello.html", "<h1>Hello</h1>{% block content %}in block{% endblock %}");
// Render a template with an empty context
let output = tera.render_block("hello.html", "content", &Context::new()).unwrap();
assert_eq!(output, "in block");Sourcepub fn render_block_to(
&self,
template_name: &str,
block_name: &str,
context: &Context,
write: impl Write,
) -> Result<(), Error>
pub fn render_block_to( &self, template_name: &str, block_name: &str, context: &Context, write: impl Write, ) -> Result<(), Error>
Renders a block by name with the given context to something that implements Write.
§Examples
let mut tera = Tera::default();
tera.add_raw_template("hello.html", "<h1>Hello</h1>{% block content %}in block{% endblock %}");
let mut buffer = Vec::new();
tera.render_block_to("hello.html", "content", &Context::new(), &mut buffer).unwrap();
assert_eq!(buffer, b"in block");Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for Tera
impl !UnwindSafe for Tera
impl Forget for Tera
impl Freeze for Tera
impl Move for Tera
impl Send for Tera
impl Sync for Tera
impl Unpin for Tera
impl UnsafeUnpin for Tera
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);