pub struct Kwargs { /* private fields */ }
Expand description
Utility to accept keyword arguments.
Keyword arguments are represented as regular values as the last argument
in an argument list. This can be quite complex to use manually so this
type is added as a utility. You can use get
to fetch a
single keyword argument and then use assert_all_used
to make sure extra arguments create an error.
Here an example of a function modifying values in different ways.
use minijinja::value::{Value, Kwargs};
use minijinja::Error;
fn modify(mut values: Vec<Value>, options: Kwargs) -> Result<Vec<Value>, Error> {
// get pulls a parameter of any type. Same as from_args. For optional
// boolean values the type inference is particularly convenient.
if let Some(true) = options.get("reverse")? {
values.reverse();
}
if let Some(limit) = options.get("limit")? {
values.truncate(limit);
}
options.assert_all_used()?;
Ok(values)
}
If for whatever reason you need a value again you can use Into
to
convert it back into a Value
.
Implementations§
source§impl Kwargs
impl Kwargs
sourcepub fn from_args(args: &[Value]) -> (&[Value], Kwargs)
pub fn from_args(args: &[Value]) -> (&[Value], Kwargs)
Split off kwargs from args.
This is useful when Rest
is used to consume all arguments:
fn my_func(args: Rest<Value>) -> Value {
let (args, kwargs) = Kwargs::from_args(&args);
// do something with args and kwargs
}
sourcepub fn peek<'a, T>(&'a self, key: &'a str) -> Result<T, Error>where
T: ArgType<'a, Output = T>,
pub fn peek<'a, T>(&'a self, key: &'a str) -> Result<T, Error>where T: ArgType<'a, Output = T>,
Get a single argument from the kwargs but don’t mark it as used.
sourcepub fn get<'a, T>(&'a self, key: &'a str) -> Result<T, Error>where
T: ArgType<'a, Output = T>,
pub fn get<'a, T>(&'a self, key: &'a str) -> Result<T, Error>where T: ArgType<'a, Output = T>,
Gets a single argument from the kwargs and marks it as used.
This method works pretty much like from_args
and marks any parameter
used internally. For optional arguments you would typically use
Option<T>
and for non optional ones directly T
.
Examples:
// f(int=42) -> Some(42)
// f() -> None
let optional_int: Option<u32> = kwargs.get("int")?;
// f(int=42) -> 42
// f() -> Error
let required_int: u32 = kwargs.get("int")?;
If you don’t want to mark it as used, us peek
instead.
sourcepub fn assert_all_used(&self) -> Result<(), Error>
pub fn assert_all_used(&self) -> Result<(), Error>
Asserts that all kwargs were used.