pub struct ValueOrKwargs(/* private fields */);Expand description
An argument value that can explicitly capture keyword arguments.
Regular Value arguments reject the internal keyword-argument value so
that misspelled or unsupported keyword arguments do not get accepted as a
positional value. Use this wrapper with Rest when implementing a
variadic function that needs to split positional and keyword arguments.
Implementations§
Source§impl ValueOrKwargs
impl ValueOrKwargs
Sourcepub fn into_value(self) -> Value
pub fn into_value(self) -> Value
Consumes the wrapper and returns the underlying value.
Methods from Deref<Target = Value>§
Sourcepub fn kind(&self) -> ValueKind
pub fn kind(&self) -> ValueKind
Returns the kind of the value.
This can be used to determine what’s in the value before trying to perform operations on it.
Sourcepub fn is_integer(&self) -> bool
pub fn is_integer(&self) -> bool
Returns true if the number is a real integer.
This can be used to distinguish 42 from 42.0. For the most part
the engine keeps these the same.
Sourcepub fn is_true(&self) -> bool
pub fn is_true(&self) -> bool
Is this value considered true?
The engine inherits the same behavior as Jinja2 when it comes to
considering objects true. Empty objects are generally not considered
true. For custom objects this is customized by Object::is_true.
Sourcepub fn is_undefined(&self) -> bool
pub fn is_undefined(&self) -> bool
Returns true if this value is undefined.
Sourcepub fn to_str(&self) -> Option<Arc<str>>
pub fn to_str(&self) -> Option<Arc<str>>
If the value is a string, return it.
This will also perform a lossy string conversion of bytes from utf-8.
Sourcepub fn as_str(&self) -> Option<&str>
pub fn as_str(&self) -> Option<&str>
If the value is a string, return it.
This will also return well formed utf-8 bytes as string.
Sourcepub fn as_object(&self) -> Option<&DynObject>
pub fn as_object(&self) -> Option<&DynObject>
If the value is an object a reference to it is returned.
The returned value is a reference to a type erased DynObject.
For a specific type use downcast_object
instead.
Sourcepub fn len(&self) -> Option<usize>
pub fn len(&self) -> Option<usize>
Returns the length of the contained value.
Values without a length will return None.
let seq = Value::from(vec![1, 2, 3, 4]);
assert_eq!(seq.len(), Some(4));Sourcepub fn get_attr(&self, key: &str) -> Result<Value, Error>
pub fn get_attr(&self, key: &str) -> Result<Value, Error>
Looks up an attribute by attribute name.
This this returns UNDEFINED when an invalid key is
resolved. An error is returned if the value does not contain an object
that has attributes.
let ctx = minijinja::context! {
foo => "Foo"
};
let value = ctx.get_attr("foo")?;
assert_eq!(value.to_string(), "Foo");Sourcepub fn get_item_by_index(&self, idx: usize) -> Result<Value, Error>
pub fn get_item_by_index(&self, idx: usize) -> Result<Value, Error>
Looks up an index of the value.
This is a shortcut for get_item.
let seq = Value::from(vec![0u32, 1, 2]);
let value = seq.get_item_by_index(1).unwrap();
assert_eq!(value.try_into().ok(), Some(1));Sourcepub fn get_item(&self, key: &Value) -> Result<Value, Error>
pub fn get_item(&self, key: &Value) -> Result<Value, Error>
Looks up an item (or attribute) by key.
This is similar to get_attr but instead of using
a string key this can be any key. For instance this can be used to
index into sequences. Like get_attr this returns
UNDEFINED when an invalid key is looked up.
let ctx = minijinja::context! {
foo => "Foo",
};
let value = ctx.get_item(&Value::from("foo")).unwrap();
assert_eq!(value.to_string(), "Foo");Sourcepub fn try_iter(&self) -> Result<ValueIter, Error>
pub fn try_iter(&self) -> Result<ValueIter, Error>
Iterates over the value.
Depending on the kind of the value the iterator
has a different behavior.
ValueKind::Map: the iterator yields the keys of the map.ValueKind::Seq/ValueKind::Iterable: the iterator yields the items in the sequence.ValueKind::String: the iterator yields characters in a string.ValueKind::None/ValueKind::Undefined: the iterator is empty.
let value = Value::from({
let mut m = std::collections::BTreeMap::new();
m.insert("foo", 42);
m.insert("bar", 23);
m
});
for key in value.try_iter()? {
let value = value.get_item(&key)?;
println!("{} = {}", key, value);
}Sourcepub fn reverse(&self) -> Result<Value, Error>
pub fn reverse(&self) -> Result<Value, Error>
Returns a reversed view of this value.
This is implemented for the following types with the following behaviors:
- undefined or none: value returned unchanged.
- string and bytes: returns a reversed version of that value
- iterables: returns a reversed version of the iterable. If the iterable is not reversible itself, it consumes it and then reverses it.
- maps: returns the keys in reverse order.
Sourcepub fn downcast_object_ref<T>(&self) -> Option<&T>where
T: 'static,
pub fn downcast_object_ref<T>(&self) -> Option<&T>where
T: 'static,
Returns some reference to the boxed object if it is of type T, or None if it isn’t.
This is basically the “reverse” of from_object
and from_dyn_object. It’s also a shortcut for
downcast_ref on the return value of
as_object.
§Example
use std::fmt;
#[derive(Debug)]
struct Thing {
id: usize,
}
impl Object for Thing {}
let x_value = Value::from_object(Thing { id: 42 });
let thing = x_value.downcast_object_ref::<Thing>().unwrap();
assert_eq!(thing.id, 42);Sourcepub fn downcast_object<T>(&self) -> Option<Arc<T>>where
T: 'static,
pub fn downcast_object<T>(&self) -> Option<Arc<T>>where
T: 'static,
Like downcast_object_ref but returns
the actual object.
Sourcepub fn call(
&self,
state: &mut State<'_, '_>,
args: &[Value],
) -> Result<Value, Error>
pub fn call( &self, state: &mut State<'_, '_>, args: &[Value], ) -> Result<Value, Error>
Calls the value directly.
If the value holds a function or macro, this invokes it. Note that in
MiniJinja there is a separate namespace for methods on objects and callable
items. To call methods (which should be a rather rare occurrence) you
have to use call_method.
The args slice is for the arguments of the function call. To pass
keyword arguments use the Kwargs type.
Usually the state is already available when it’s useful to call this method,
but when it’s not available you can get a fresh template state straight
from the Template via new_state.
let func = Value::from_function(|v: i64, kwargs: Kwargs| {
v * kwargs.get::<i64>("mult").unwrap_or(1)
});
let rv = func.call(
state,
&[
Value::from(42),
Value::from(Kwargs::from_iter([("mult", Value::from(2))])),
],
).unwrap();
assert_eq!(rv, Value::from(84));With the args! macro creating an argument slice is
simplified:
let func = Value::from_function(|v: i64, kwargs: Kwargs| {
v * kwargs.get::<i64>("mult").unwrap_or(1)
});
let rv = func.call(state, args!(42, mult => 2)).unwrap();
assert_eq!(rv, Value::from(84));Sourcepub fn call_method(
&self,
state: &mut State<'_, '_>,
name: &str,
args: &[Value],
) -> Result<Value, Error>
pub fn call_method( &self, state: &mut State<'_, '_>, name: &str, args: &[Value], ) -> Result<Value, Error>
Calls a method on the value.
The name of the method is name, the arguments passed are in the args
slice. Method lookup first tries methods implemented by the object, then
the environment’s unknown method callback, and finally a callable value
stored under name on the object.
Trait Implementations§
Source§impl<'a> ArgType<'a> for ValueOrKwargs
impl<'a> ArgType<'a> for ValueOrKwargs
Source§type Output = ValueOrKwargs
type Output = ValueOrKwargs
Source§impl Clone for ValueOrKwargs
impl Clone for ValueOrKwargs
Source§fn clone(&self) -> ValueOrKwargs
fn clone(&self) -> ValueOrKwargs
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for ValueOrKwargs
impl Debug for ValueOrKwargs
Source§impl Deref for ValueOrKwargs
impl Deref for ValueOrKwargs
Source§impl From<Value> for ValueOrKwargs
impl From<Value> for ValueOrKwargs
Source§fn from(value: Value) -> ValueOrKwargs
fn from(value: Value) -> ValueOrKwargs
Source§impl From<ValueOrKwargs> for Value
impl From<ValueOrKwargs> for Value
Source§fn from(value: ValueOrKwargs) -> Value
fn from(value: ValueOrKwargs) -> Value
Auto Trait Implementations§
impl !RefUnwindSafe for ValueOrKwargs
impl !UnwindSafe for ValueOrKwargs
impl Forget for ValueOrKwargs
impl Freeze for ValueOrKwargs
impl Move for ValueOrKwargs
impl Send for ValueOrKwargs
impl Sync for ValueOrKwargs
impl Unpin for ValueOrKwargs
impl UnsafeUnpin for ValueOrKwargs
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<I> FunctionResult for I
impl<I> FunctionResult for I
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);