Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

运行时 Values

可以在运行时定义变量,并通过 value 过滤器或 askama::get_value 函数在模板中使用它们,还可以调用 render 方法的 _with_values 变体。这些方法需要一个额外参数,该参数需实现 Values trait。std库提供的几种类型(如 HashMap)已实现了该 trait

#![allow(unused)]
fn main() {
use std::collections::HashMap;

let mut values: HashMap<&str, Box<dyn Any>> = HashMap::new();
// We add a new value named "name" with the value "Bibop".
values.insert("name", Box::new("Bibop"));
values.insert("age", Box::new(12u32));
}

Values trait 期望存储的数据类型能够配合 Any trait,从而允许存储任意类型的值。

然后,使用这些值进行渲染:

#![allow(unused)]
fn main() {
template_struct.render_with_values(&values).unwrap();
}

有两种方式可以从模板中获取这些值:一种是使用 value 过滤器,另一种是直接调用 askama::get_value 函数:

{% if let Ok(name) = "name"|value::<&str> %}
  name is {{ name }}
{% endif %}
{% if let Ok(age) = askama::get_value::<u32>("age") %}
  age is {{ age }}
{% endif %}

如果尝试用错误的类型获取值,或者获取一个未设置的值,将得到 Err(askama::Error::ValueType)Err(askama::Error::ValueMissing)

另一个使用键值元组的示例:

#![allow(unused)]
fn main() {
let value = "value".to_string();
let tuple: (&str, &dyn Any) = ("a", &value);

template_struct.render_with_values(&tuple).unwrap();
}

这样的设置下,只有键 "a" 会返回一个值:

{% if let Ok(name) = "a"|value::<String> %}
  a is {{ a }}
{% endif %}