tera/macros.rs
1/// Helper macro to get real values out of Value while retaining
2/// proper errors in filters
3///
4/// Takes 4 args:
5///
6/// - the filter name,
7/// - the variable name: use "value" if you are using it on the variable the filter is ran on
8/// - the expected type
9/// - the actual variable
10///
11/// ```no_compile
12/// let arr = try_get_value!("first", "value", Vec<Value>, value);
13/// let val = try_get_value!("pluralize", "suffix", String, val.clone());
14/// ```
15#[macro_export]
16macro_rules! try_get_value {
17 ($filter_name:expr, $var_name:expr, $ty:ty, $val:expr) => {{
18 match $crate::from_value::<$ty>($val.clone()) {
19 Ok(s) => s,
20 Err(_) => {
21 if $var_name == "value" {
22 return Err($crate::Error::msg(format!(
23 "Filter `{}` was called on an incorrect value: got `{}` but expected a {}",
24 $filter_name, $val, stringify!($ty)
25 )));
26 } else {
27 return Err($crate::Error::msg(format!(
28 "Filter `{}` received an incorrect type for arg `{}`: got `{}` but expected a {}",
29 $filter_name, $var_name, $val, stringify!($ty)
30 )));
31 }
32 }
33 }
34 }};
35}