Tera-in-Rocket-registers-global-functions
1.介绍
函数register_function
pub fn register_function<F: Function + 'static>(&mut self, name: &str, function: F) {
self.functions.insert(name.to_string(), Arc::new(function));
}
其中,Function
pub trait Function: Sync + Send {
fn call(
&self,
args: &HashMap<String, Value, RandomState>
) -> Result<Value, Error>;
fn is_safe(&self) -> bool { ... }
}
2.实践
info.rs
use rocket_dyn_templates::tera::Result;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct BlogInfo {
//
}
pub fn blog_info(_args: &HashMap<String, Value>) -> Result<Value> {
//
Ok(json!(info))
}
特别注意Result:
use rocket_dyn_templates::tera::Result;
main.rs
rocket::build()
.mount(
//
)
.attach(Template::custom(|engines| {
engines.tera.register_function("blog_info", info::blog_info);
}))
由于函数返回的是json,在.tera文件中使用get方法获取值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{blog_info() | get(key="title") }}</title>
</head>
<body>
</body>
</html>
参考:
1.Rust模板引擎Tera中文英文对照官方文档
2.Registering a Tera template function with Rocket
最后修改: 2022-08-15T21:28:42
版权声明:署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
comment 评论