使用方法
通常我们使用Tera去解析一个目录下的全部模板文件,还是举个例子更好理解,就比如我们有下面这样的一个目录,用来保存模板文件:
The primary method of using Tera is to load and parse all the templates in a given glob.
Let's take the following directory as example.
templates/
hello.html
index.html
products/
product.html
price.html
假设这个templates文件夹,跟Rust项目的源码文件夹src在同一个目录里,我们就可以像下面这样去实例化Tera:
Assuming the Rust file is at the same level as the templates folder, we can get a Tera instance that way:
use tera::Tera;
// 整个项目中就使用这一个tera就可以了
let tera = match Tera::new("templates/**/*.html") {
Ok(t) => t,
Err(e) => {
println!("Parsing error(s): {}", e);
::std::process::exit(1);
}
};
实例化Tera对象解析编译模板文件一次也就够了,不用每次使用都重新创建个Tera实例,我们可以使用lazy_static去创建一个只解析一次模板实例化一次整个项目中都能用的Tera实例(懒汉单例模式)
Compiling templates is a step that is meant to only happen once: use something like lazy_static
to define a constant instance.
lazy_static! {
pub static ref TEMPLATES: Tera = {
let mut tera = match Tera::new("examples/basic/templates/**/*") {
Ok(t) => t,
Err(e) => {
println!("Parsing error(s): {}", e);
::std::process::exit(1);
}
};
tera.autoescape_on(vec!["html", ".sql"]);
tera.register_filter("do_nothing", do_nothing_filter);
tera
};
}
使用Tera渲染一个模板文件需要俩个参数:一个是模板的名称,另一个是模板上下文对象
You need two things to render a template: a name and a context.
模板名称可以直接写文件的名称,不需要带前面的共有路径templates,比如要使用模板templates/hello.html只需要写hello.html,当然你得是按照上面的方式实例化的tera
If you are using globs, Tera will automatically remove the glob prefix from the template names. To use our example from before,
the template name for the file located at templates/hello.html will be hello.html.
那咋子创建上下文对象呢?
上下文对象可以是任何实现了serde_json提供的Serialize特征的结构体对象也可以是类型tera::Context的实例化对象。
实例化对象如果不会请右转参考零基础学新时代编程语言Rust
The context can either a be data structure that implements the Serialize trait from serde_json or an instance of tera::Context: