来嘞早不如来的巧,刚翻译好,你就来啦!翻译完成
要开发CMS(内容管理系统)得有个模板引擎,Tera是使用Rust编写的模板引擎,语法跟JinJa2很像。
要使用Tera只需要在 Cargo.toml中添加:
tera = "1"
是不是很简单_?
默认情况下, Tera会引入一些依赖比如: truncate, date, filesizeformat slugify, urlencode 和 urlencode_strict ,这些依赖是某些过滤器(后面会讲解)要用的. 如果你确定不需要可以在 Cargo.toml中这么配置:
[dependencies.tera]
version = "1"
default-features = false
如果你用的Rust不是2018版本的(你最好使用),你需要在lib.rs或者main.rs文件中写上
And add the following to your lib.rs or main.rs if you are not using Rust 2018:
extern crate tera;
2018版本就不需要这样写了,原因可以参考零基础学新时代编程语言Rust
如果想了解Tera的API可以看API文档
You can view everything Tera exports on the API docs.
通常我们使用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:
use tera::Context;
//使用tera提供的Context结构体创建上下文对象
// Using the tera Context struct
let mut context = Context::new();
context.insert("product", &product);
context.insert("vat_rate", &0.20);
tera.render("products/product.html", &context)?;
//使用实现了Serialize特征的结构体创建上下文对象
#[derive(Serialize)]
struct Product {
name: String
}
// or a struct
tera.render("products/product.html", &Context::from_serialize(&product)?)?;
默认情况下,Tera会对文件名称结尾是.html, .html和.xml的文件中的内容进行转义处理。如果想了解Tera处理的方式可以看这里OWASP.
By default, Tera will auto-escape all content in files ending with ".html", ".htm" and ".xml".
Escaping follows the recommendations from OWASP.
如果想自己定义那些文件需要转义可以使用autoescape_on方法
You can override that or completely disable auto-escaping by calling the autoescape_on method:
//只转义文件名结尾是.php.html的文件
// escape only files ending with `.php.html`
tera.autoescape_on(vec![".php.html"]);
//不转义任何文件
// disable autoescaping completely
tera.autoescape_on(vec![]);
实例扩展(Extending another instance)
如果你使用的框架或者库已经使用了tera,它定义了自己模板、过滤器、全局函数或者测试器,我们能不能直接复用人家定义好的配置呢?
这就要用到extend方法了,使用它可以用一个先前已经存在的tera实例去扩展我们新创建的实例。
If you are using a framework or a library using Tera, chances are they provide their own Tera instance with some
built-in templates, filters, global functions or testers. Tera offers a extend method that will extend your own
instance with everything mentioned before:
let mut tera = Tera::new(&tpl_glob).chain_err(|| "Error parsing templates")?;
//这里的ZOLA_TERA是外部库已经定义好的Tera实例
// ZOLA_TERA is an instance present in a library
tera.extend(&ZOLA_TERA)?;
如果在自己定义的Tera实例和扩展用的Tera实例存在同名的模板文件或过滤器什么的会发生啥子?
如果有同名的会使用自己定义的。
If anything - templates, filters, etc - with the same name exists in both instances, Tera will only keep yours.
怎么做到模板文件夹中的文件一旦有变动(修改、新增、移动模板文件),就重新加载解析模板文件呢?
可以使用Tera提供的full_reload方法
If you are watching a directory and want to reload templates on change (editing/adding/removing a template), Tera gives
the full_reload method:
tera.full_reload()?;
注意啦!
自动重新加载模板文件功能,只在使用全局tera加载模板文件的方式才能用哦!
Note that reloading is only available if you are loading templates with a glob.
直接使用字符串做为模板(Loading templates from strings)
Tera不但支持前面显示的把文件作为模板,还支持把字符串作为模板,很强很方便有木有?
Tera allows you load templates not only from files but also from plain strings.
//只使用字符串设置一个模板
// one template only
let mut tera = Tera::default();
tera.add_raw_template("hello.html", "the body")?;
//使用字符串设置多个模板
// many templates
let mut tera = Tera::default();
tera.add_raw_templates(vec![
("grandparent", "{% block hey %}hello{% endblock hey %}"),
("parent", "{% extends \"grandparent\" %}{% block hey %}Parent{% endblock hey %}"),
])?;
如果模板间有集成关系,比如一个模板继承于另一个模板,这个时候你需要使用`add_raw_templates`把模板一起加进来,不然Tera由于找不到被依赖的模板文件就该报错了。
**Tera:你说你想要吃个茶叶蛋,可只给俺几片茶叶,你是几个意思?**
>If some templates are related, for example one extending the other, you will need to the `add_raw_templates` method
as Tera will error if it find inconsistencies such as extending a template that Tera doesn't know about.
### 临时渲染个模板(Render a one off template)
有些时候我们需要临时渲染个模板,比如用户提交个模板让临时渲染下,这该咋办呢?我们先前的模板都是提交加载好的啊,可以告诉用户不能这么玩,也可以使用`one_off`函数
>Want to render a single template, for example one coming from a user? The `one_off` function is there for that.
```rs
//one_off函数的最后一个参数是设置是否需要对模板中的内容进行转义的。
//如果不知道咋设置就直接设置成true,有99%的把握没错!
// The last parameter is whether we want to autoescape the template or not.
// Should be true in 99% of the cases for HTML
let context = Context::new();
// add stuff to context
let result = Tera::one_off(user_tpl, context, true);
Tera模板就是一些包含变量和表达式的文本文件,这些变量和表达会在渲染的时候根据上下文中的数据替换掉。模板的语法跟Jinja2和Django模板很像。
A Tera template is just a text file where variables and expressions get replaced with values
when it is rendered. The syntax is based on Jinja2 and Django templates.
在模板文件中有三种特殊标记
There are 3 kinds of delimiter and those cannot be changed:
用于表示里面是表达式的{{和}}
{{ and }} for expressions
用于表示里面是(声明)语句的{%或{%-和%} 或者-%}
语句和表达式的区别可参考零基础学新时代编程语言Rust
{% or {%- and %} or -%} for statements
用于标示里面是注释的 {#和#}
{# and #} for comments
那如果要渲染的内容中恰巧包含上面提到的3种特殊标记咋办呢?
可以使用raw块输出, Tera会把raw块中的内容当成是字符串原样输出。
Tera will consider all text inside the raw block as a string and won’t try to
render what’s inside. Useful if you have text that contains Tera delimiters.
{% raw %}
Hello {{ name }}
{% endraw %}
渲染的结果为Hello {{name}}
would be rendered as Hello {{ name }}.
使用Tera提供的{%-和-%}可以很方便的分别去除内容左边和右边的空白。
Tera comes with easy to use whitespace control: use {%- if you want to remove all whitespace
before a statement and -%} if you want to remove all whitespace after.
还是来个例子吧,比如有个模板像下面这样写的:
For example, let’s look at the following template:
{% set my_var = 2 %}
{{ my_var }}
//渲染效果像下面这样:
will have the following output:
如果我们需要去除内容右边出现的空白行,就可以像下面这样写:
If we want to get rid of the empty line, we can write the following:
{% set my_var = 2 -%}
{{ my_var }}
模板嘛也是代码,代码嘛总要有点注释才完整嘛。在Tera模板中可以把注释写在{#和#}之间。
To comment out part of the template, wrap it in {# #}. Anything in between those tags
will not be rendered.
{# A comment #}
Tera支持以下几种字面量:
Tera has a few literals that can be used:
布尔字面量:true和false
booleans: true and false
整型字面量(整型不是整形,一个是数字一个是要钱)
integers
浮点数字面量
floats
字符串字面量,就是包含在""或者''或者backticks中的
strings: text delimited by "", '' or backticks
数组:就是把字面量包含在[和]中,如果有多个就用逗号分开
arrays: a list of literals and/or idents by [ and ] and comma separated (trailing comma allowed)
变量是在渲染模板时由上下文提供的,如果你想在模板中定义变量可以看下这里
Variables are defined by the context given when rendering a template. If you’d like to define your own variables, see the Assignments section.
我们可以像下面这样渲染变量:
{{name}}
You can render a variable by using the {{ name }}.
如果渲染的变量不存在就会报错
Trying to access or render a variable that doesn’t exist will result in an error.
如果需要看下模板当前的上下文对象可以使用一个神奇的变量:__tera_context
A magical variable is available in every template if you want to print the current context: __tera_context.
可以使用.访问某个对象的某个属性,比如要渲染出product的name属性可以这么写:
{{product.name}}
也可以使用.索引编号的形式访问数组或元组中的某个元素,索引编号从0开始,也就是数组或元组中的第1个元素的索引编号是0
Construct and attributes can be accessed by using the dot (.) like {{ product.name }}.
Specific members of an array or tuple are accessed by using the .i notation, where i is a zero-based index.
符号[](Square bracket notation):
使用[]可以替代.用于获取某个对象的某个属性,比如上面提到获取product的name属性的例子,也可以这样写:
{{product['name']}}
还可以这样写:
`{{product[“name”]}}
A more powerful alternative to (.) is to use square brackets ([ ]).
Variables can be rendering using the notation {{product['name']}} or {{product["name"]}}.
那使用[]有没有更强大的功能?
有的,这也是[]存在的理由,不然直接用.不就行了。
在有些时候我们并不确定需要具体访问对象的那个属性,也就是对象的属性名称是个变量。可以考虑下使用.该怎么写?
使用[]就可以先定义个变量用于存储具体的属性名称,比如定义个my_field:
my_field = "name"
然后可以在[]使用这个变量:
{{product[my_field]}}
这跟{{product.name}}实现的功能一样。
注意:
如果在[]中使用变量,不需要使用'或"
If the item is not in quotes it will be treated as a variable.
Assuming you have the following objects in your context product = Product{ name: "Fred" }
and my_field = "name", calling {{product[my_field]}} will resolve to: {{product.name}}.
另外如果是索引值必须是能转换为数字的字符串,如果不能转换为数字就该报错了。
Only variables evaluating to String and Number can be used as index: anything else will be
an error.
在Tera中几乎任何地方都可以使用表达式
Tera allows expressions almost everywhere.
你可以使用Tera做一些基本的数字运行,但是不要乱用,比如像这么写+1,除了让代码难看了点没啥用。
需要注意的是只能对数字进行数字运行,如果对其它类型的数据进行数字运行会报错的哦!
Tera支持的数字运算符有:
You can do some basic math in Tera but it shouldn’t be abused other than the occasional + 1 or similar.
Math operations are only allowed with numbers, using them on any other kind of values will result in an error.
You can use the following operators:
+: 把2个数字加起来,也就是求俩个数字的和,比如: {{ 1 + 1 }} 输出结果是 2
+: adds 2 values together, {{ 1 + 1 }} will print 2
-: 求俩个数字的差,比如:{{ 2 - 1 }} 输出结果是1
-: performs a substraction, {{ 2 - 1 }} will print 1
/: 用于执行除法运算,比如{{ 10 / 2 }} 输出结果是 5
/: performs a division, {{ 10 / 2 }} will print 5
*:用于执行乘法运算, 比如{{ 5 * 2 }} 输出结果是 10
*: performs a multiplication, {{ 5 * 2 }} will print 10
%: 用于执行取余(取模)运行,比如{{ 2 % 2 }} 输出结果是0
%: performs a modulo, {{ 2 % 2 }} will print 0
运算符的执行优先级(从低到高):
The priority of operations is the following, from lowest to highest:
+ 和 -
+ and -
* 和 / 和 %
* and / and %
就是我们读小学背的先乘除后加减
==: 用于判断俩个数据是不是相等的
!=: 用于判断俩个数据是不是不相等的
>=: 大于等于判断操作符
<=: 小于等于判断操作符
>: 大于判断操作符
<: 小于判断操作符
and: 与操作符 只有两边都为true时结果才为true
or: 或操作符 只要俩边有任意一个为true结果就为true
not: 非操作符 取反操作
可以使用~把多个字符串或标示符连接在一起
You can concatenate several strings/idents using the ~ operator.
{{ "hello " ~ 'world' ~ `!` }}
{{ an_ident ~ " and a string" ~ another_ident }}
{{ an_ident ~ another_ident }}
注意
如果标示符对应的值不是字符串就会报错哦!
An ident resolving to something other than a string will raise an error.
可以使用in判断右边是否包含左边
You can check whether a left side is contained in a right side using the in operator.
{{ some_var in [1, 2, 3] }}
{{ 'index' in page.path }}
{{ an_ident not in an_obj }}
1
2
3
4
5
注意
in的右边只能是包含字面量、变量的数组或者是字符串或者对象,如果是其它类型就该报错了哦!
Only literals/variables resulting in an array, a string and an object are supported in the right hand side: everything else
will raise an error.
可以在渲染的时候把一个值赋值给一个变量
在for循环和宏中的赋值只在其中有效,在其它地方的赋值全局有效
You can assign values to variables during the rendering.
Assignments in for loops and macros are scoped to their context but
assignments outside of those will be set in the global context.
{% set my_var = "hello" %}
{% set my_var = 1 + 4 %}
{% set my_var = some_var %}
{% set my_var = macros::some_macro() %}
{% set my_var = global_fn() %}
{% set my_var = [1, true, some_var | round] %}
如果需要在for循环中进行全局有效的赋值,可以使用set_global
If you want to assign a value in the global context while in a for loop, you can use set_global:
{% set_global my_var = "hello" %}
{% set_global my_var = 1 + 4 %}
{% set_global my_var = some_var %}
{% set_global my_var = macros::some_macro() %}
{% set_global my_var = global_fn() %}
{% set_global my_var = [1, true, some_var | round] %}
1
2
3
4
5
6
在for循环外部使用set_global效果跟set一样
Outside of a for loop, set_global is exactly the same as set.
可以使用过滤器修改变量
在变量名称后面添加一个|,再后面就可以跟上过滤器名称和参数(如果有)来使用过滤器了。
可以一次使用多个过滤器,前面过滤器的输出是后面过滤器的输入.
You can modify variables using filters.
Filters are separated from the variable by a pipe symbol (|) and may have named arguments in parentheses.
Multiple filters can be chained: the output of one filter is applied to the next.
有没有晕?接触过AngularJS没?还是举个例子吧:
{{ name | lower | replace(from="doctor", to="Dr.") }}
把名称全小写,然后再把包含的"doctor"替换为"Dr.";
如果name是"doctor ZhanSan" 那输出的结果就是:Dr. zhansan
如果你不习惯又不能接受这种书写风格,也可以像下面这样写:
replace(lower(name), from="doctor", to="Dr.")
看着就跟函数调用似的.
For example, {{ name | lower | replace(from="doctor", to="Dr.") }} will take a variable called name, make it lowercase and then replace instances of doctor by Dr..
It is equivalent to replace(lower(name), from="doctor", to="Dr.") if we were to look at it as functions.
注意
使用过滤器时要确保数据类型是符合当前过滤器需要的,如果不符合就会报错哦!
比如在数组类型的数据上使用首字母大小过滤器,就会报错!
Calling filters on a incorrect type like trying to capitalize an array or using invalid types for arguments will result in a error.
怎么自定义过滤器呢?
可以定义类型为fn(Value, HashMap<String, Value>) -> Result<Value>的函数,再调用Tera实例的rigister_filter方法注册下,就可以在模板中
使用自定义的过滤器了
Filters are functions with the fn(Value, HashMap<String, Value>) -> Result<Value> definition and custom ones can be added like so:
tera.register_filter("upper", string::upper);
过滤器也可以跟数字计算一起使用,不过需要注意它的优先级比较低
举个例子:
While filters can be used in math operations, they will have the lowest priority and therefore might not do what you expect:
{{1 + a | length}}// 上面这段代码跟下面这段代码等价{{(1 + a)| length}// 如果你是想先对a进行过滤器处理,再对处理后的结果加1,你可以像下面这样写{{a | length + 1}}
Tera内置了一些过滤器,如果你想了解下可以看内置过滤器
Tera has many built-in filters that you can use.
包含在 {% filter name %} 和 {% endfilter %}中的内容都会被对应过滤器处理,其中name就是过滤器名称
Whole sections can also be processed by filters if they are encapsulated in {% filter name %} and {% endfilter %}
tags where name is the name of the filter:
{% filter upper %}
Hello
{% endfilter %}
示例代码是把Hello处理为HELLO也就是把包含的所有字母大写
This example transforms the text Hello in all upper-case (HELLO).
过滤器区域中还可以包含 块区域 就像这样:
Filter sections can also contain block sections like this:
{% filter upper %}
{% block content_to_be_upper_cased %}
This will be upper-cased
{% endblock content_to_be_upper_cased %}
{% endfilter %}
可以使用if和is判断一个表达式是否符合某种条件,比如下面的代码中判断一个表达式的值是否是偶数:
Tests can be used against an expression to check some condition on it and
are made in if blocks using the is keyword.
For example, you would write the following to test if an expression is odd:
{% if my_number is odd %}
Odd
{% endif %}
也可以使用方向判断,下面代码中判断一个表达式是否是奇数
Tests can also be negated:
{% if my_number is not odd %}
Even
{% endif %}
怎么自定义条件判断呢?
可以编写一个fn(Option<Value>, Vec<Value>) -> Result<bool>类型的函数,然后调用Tera实例的register_tester方法注册一下子,就可以在模板中使用了.
Tests are functions with the fn(Option<Value>, Vec<Value>) -> Result<bool> definition and custom ones can be added like so:
tera.register_tester("odd", testers::odd);
Tera也提供了些内置的条件判断,如果你想了解下可以看这里 内置的条件判断
Tera has many built-in tests that you can use.
可以使用Rust定义返回值类型为Result<Value> 函数定义可以在模板中使用的函数.
Functions are Rust code that return a Result<Value> from the given params.
通常情况下,函数都是需要额外参数的,比如全局函数url_for就需要个包含了url的列表作为参数.
Quite often, functions will need to capture some external variables, such as a url_for global function needing
the list of URLs for example.
可以定义个Box<Fn(HashMap<String, Value>) -> Result<Value> + Sync + Send>类型也就是GlobalFn类型的函数作为全局函数.比如:
To make that work, the type of GlobalFn is a boxed closure: Box<Fn(HashMap<String, Value>) -> Result<Value> + Sync + Send>.
Here’s an example on how to implement a very basic function:
fn make_url_for(urls: BTreeMap<String, String>) -> GlobalFn {
Box::new(move |args| -> Result<Value> {
match args.get("name") {
Some(val) => match from_value::<String>(val.clone()) {
Ok(v) => Ok(to_value(urls.get(&v).unwrap()).unwrap()),
Err(_) => Err("oops".into()),
},
None => Err("oops".into()),
}
})
}
别忘了,还需要调用Tera实例的register_function方法注册一下子:
You then need to add it to Tera:
tera.register_function("url_for", make_url_for(urls));
然后你就可以在模板中使用这个函数了
And you can now call it from a template:
{{/* url_for(name="home") */}}
当前在模板中的俩个地方可以调用函数:
Currently functions can be called in two places in templates:
代码块: {{/* url_for(name="home") */}}
for循环: {% for i in range(end=5) %}
Tera也内置了些函数,有兴趣可以看这里内置函数.
Tera comes with some built-in functions.
在Tera模板中可以像在Python中一样使用If
Conditionals are fully supported and are identical to the ones in Python.
{% if price < 10 or always_show %}
Price is {{ price }}.
{% elif price > 1000 and not rich %}
That's expensive!
{% else %}
N/A
{% endif %}
同样的如果变量不存在就会报错,你可以像下面这样判断一个变量是否存在
Undefined variables are considered falsy. This means that you can test for the
presence of a variable in the current context by writing:
{% if my_var %}
{{ my_var }}
{% else %}
Sorry, my_var isn't defined.
{% endif %}
还要记得每个if语句都需要一个endif做为结尾
Every if statement has to end with an endif tag.
循环遍历数组中的元素:
Loop over items in a array:
{% for product in products %}
{{loop.index}}. {{product.name}}
{% endfor %}
在循环中有一些特殊的变量可以使用:
A few special variables are available inside for loops:
loop.index: 当前遍历元素的索引值,从1开始计数
loop.index0: 当前变量元素的索引值,从0开始计数
loop.first: 当前元素是否是第一个元素
loop.last: 当前元素是否是最后一个元素
别忘了每个for语句后面要有个endfor作为结尾
Every for statement has to end with an endfor tag.
也可以使用for循环变量map和struct类型的数据,例如:
You can also loop on maps and structs using the following syntax:
{% for key, value in products %}
{{loop.index}}. {{product.name}}
{% endfor %}
key和value并不是必须要这么命名的,只要你开心,你可以命名为阿猫阿狗都可以,当然也需要顾及下看代码人的感受;
key and value can be named however you want, they just need to be separated with a comma.
在遍历数组中的每个元素的时候你还可以使用过滤器对元素进行处理:
If you are iterating on an array, you can also apply filters to the container:
{% for product in products | reverse %}
{{loop.index}}. {{product.name}}
{% endfor %}
当然你也可以遍历字面量形式的数组:
You can also iterate on array literals:
{% for a in [1,2,3,] %}
{{a}}
{% endfor %}
另外,当遍历的集合是空的时候,你也可以另外设置要渲染的内容,就像下面这样:
Lastly, you can set a default body to be rendered when the container is empty:
{% for product in products %}
{{loop.index}}. {{product.name}}
{% else %}
No products.
{% endfor %}
在循环中可以使用break和continue控制循环的执行.比如可以使用break在找到了id为target_id后就停止循环
Within a loop, break and continue may be used to control iteration.
To stop iterating when target_id is reached:
{% for product in products %}
{% if product.id == target_id %}{% break %}{% endif %}
{{loop.index}}. {{product.name}}
{% endfor %}
比如跳过奇数行:
To skip even-numbered items:
{% for product in products %}
{% if loop.index is even %}{% continue %}{% endif %}
{{loop.index}}. {{product.name}}
{% endfor %}
可以使用include引入另一个模板文件.
You can include a template to be rendered using the current context with the include tag.
{% include "included.html" %}
使用include引入的模板跟当前模板使用同一个上下文渲染,如果你想为引入的模板定义上下文可以使用macros(宏) ,Rust也是支持宏的可以参考零基础学新时代编程语言Rust
Tera doesn’t offer passing a custom context to the include tag.
If you want to do that, use macros.
在被引入的模板中使用set赋值的变量在引入模板中是不能用的。
While you can set values in included templates, those values only exist while rendering
them: the template calling include doesn’t see them.
可以把宏当成是函数或是组件,通过调用返回某些文本.
Think of macros as functions or components that you can call and return some text.
宏需要定义在一个单独的文件中,在用的时候需要引入
Macros currently need to be defined in a separate file and imported to be useable.
比如可以像下面这样定义宏:
They are defined as follows:
{% macro input(label, type="text") %}
<label>
{{ label }}
<input type="{{type}}" />
</label>
{% endmacro input %}
像上面代码演示的,宏的参数可以设置字面量默认值。
As shown in the example above, macro arguments can have a default literal value.
在使用宏的时候把包含宏的文件导入就可以了,就像下面这样:
In order to use them, you need to import the file containing the macros:
{% import "macros.html" as macros %}
在导入的时候还可以起个命名空间。
You can name that file namespace (macros in the example) anything you want.
A macro is called like this:
可以像下面这样使用宏:
// namespace::macro_name(**kwargs)
{{ macros::input(label="Name", type="text") }}
注意
调用宏时也需要正确类型的参数。
Do note that macros, like filters, require keyword arguments.
如果要调用当前文件中定义的宏可以使用self命名空间.
需要注意self命名空间只能在宏中使用
If you are trying to call a macro defined in the same file or itself, you will need to use the self namespace.
The self namespace can only be used in macros.
可以递归调用宏,所以在写代码时一定要适时的结束宏调用
Macros can be called recursively but there is no limit to recursion so make sure your macro ends.
这里有个递归调用宏的例子:
Here’s an example of a recursive macro:
{% macro factorial(n) %}
{% if n > 1 %}{{ n }} - {{ self::factorial(n=n-1) }}{% else %}1{% endif %}
{% endmacro factorial %}
在宏体内可以使用常用的Tera语法除了宏定义、block、extends
Macros body can contain all normal Tera syntax with the exception of macros definition, block and extends.
Tera也支持类似Jinja2和Django模板的集成功能:
也就是定义一个基模板然后其它模板可以继承扩展基模板。
Tera uses the same kind of inheritance as Jinja2 and Django templates:
you define a base template and extends it in child templates through blocks.
继承支持多级继承,比如A继承B,B再集成C
There can be multiple levels of inheritance (i.e. A extends B that extends C).
基模板是包含基础文档结构的模板,通常是有几个blocks组成
A base template typically contains the basic document structure as well as
several blocks that can have content.
比如:下面的base.html就是几乎从Jinja2文档中复制过来的。
For example, here’s a base.html almost copied from the Jinja2 documentation:
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock title %} - My Webpage</title>
{% endblock head %}
</head>
<body>
<div id="content">{% block content %}{% endblock content %}</div>
<div id="footer">
{% block footer %}
© Copyright 2008 by <a href="http://domain.invalid/">you</a>.
{% endblock footer %}
</div>
</body>
</html>
跟Jinja2不一样的是,在endblock中需要提供一个名称。
The only difference with Jinja2 being that the endblock tags have to be named.
这个base.html模板定义了4个block,子模板可以根据自己的使用需要覆盖block。
其中head和footer块在基模板中已经定义的内容,也可以在子模板中重新定义.
This base.html template defines 4 block tag that child templates can override.
The head and footer block have some content already which will be rendered if they are not overridden.
同样的,子模板跟Jinja2里用法也差不多:
Again, straight from Jinja2 docs:
{% extends "base.html" %}
{% block title %}Index{% endblock title %}
{% block head %}
{{/* super() */}}
<style type="text/css">
.important { color: #336699; }
</style>
{% endblock head %}
{% block content %}
<h1>Index</h1>
<p class="important">
Welcome to my awesome homepage.
</p>
{% endblock content %}
为了实现继承需要在模板文件的最上面使用extends标签声明要继承的模板.
可以在子模板中使用 {{/* super() */}}告诉Tera我们想在这个地方渲染基模板的块(block)
To indicate inheritance, you have use the extends tag as the first thing in the file followed by the name of the template you want
to extend.
The {{/* super() */}} variable call tells Tera to render the parent block there.
在Tera中块也是可以嵌套使用的,像下面这样:
Nested blocks also work in Tera. Consider the following templates:
// grandparent
{% block hey %}hello{% endblock hey %}
// parent
{% extends "grandparent" %}
{% block hey %}hi and grandma says {{/* super() */}} {% block ending %}sincerely{% endblock ending %}{% endblock hey %}
// child
{% extends "parent" %}
{% block hey %}dad says {{/* super() */}}{% endblock hey %}
{% block ending %}{{/* super() */}} with love{% endblock ending %}
```
块`ending`嵌套在块`hey`中。Tera在渲染模板`child`的过程是这个样子地:
The block `ending` is nested in the `hey` block. Rendering the `child` template will do the following:
- 查找基模板: `grandparent`
- 查看块 `hey` 是否包含在模板`child` 和`parent` 中
- 在模板`child` 中找到了块`hey`就渲染它, 在块`hey`中调用了`super()`所以我们需要渲染模板`parent`的块 `hey` ,模板`parent`的块 `hey`也调用了`super()`,所以我们还需要渲染模板 `grandparent`的块`hey`
- 接下来在模板`child`中查找块 `ending` 并渲染它,它里面也调用了 `super()`所以还需要渲染模板`parent`的块`ending`
最后执行结果(不包括空内容)就是:"dad says hi and grandma says hello sincerely with love".
>The end result of that rendering (not counting whitespace) will be: "dad says hi and grandma says hello sincerely with love".
## 内置的那些事(Built-ins)
### 内置的过滤器(Built-in filters)
Tera内置了以下过滤器:
>Tera has the following filters built-in:
#### lower
把字符串中的所有字符进行小写
>Lowercase a string
#### wordcount
计算字符串中的词个数
>Returns number of words in a string
#### capitalize
字符串的首字母大写
>Returns the string with all its character lowercased apart from the first char which is uppercased.
#### replace
字符串替换过滤器,过滤器有俩个参数`from`和`to`,也就是把字符串包含的from字符串替换为to字符串。
>Takes 2 mandatory string named arguments: `from` and `to`. It will return a string with all instances of
the `from` string with the `to` string.
比如: `{{ name | replace(from="Robert", to="Bob")}}`
如果name的值是"Hello Robert"结果就是"Hello Bob"
#### addslashes
在引号前添加斜杠
>Adds slashes before quotes.
比如: `{{ value | addslashes }}`
如果value的值是 "I'm using Tera"那结果就是: "I\\'m using Tera".
#### slugify
要使用这个过滤器需要启用`builtins` feature
>Only available if the `builtins` feature is enabled.
这个过滤器的效果是把字符串转换为ASCII码然后再把所有字符小写、去掉首未的空白字符、再把包含的空字符替换为'-'
然后去除所有不是小写字母又不是数字又不是`-`的字符;
>Transform a string into ASCII, lowercase it, trim it, converts spaces to hyphens and
>remove all characters that are not numbers, lowercase letters or hyphens.
比如: `{{ value | slugify }}`
如果value的值是 "-Hello world! "执行的结果就是:"hello-world".
#### title
把字符串中包含的每个词的第一个字母转换为大写的形式
>Capitalizes each word inside a sentence.
比如: `{{ value | title }}`
如果value的值是 "foo bar", 执行结果就是"Foo Bar".
#### trim
移除字符串前面和后面的空白字符
>Remove leading and trailing whitespace if the variable is a string.
#### trim_start
只移除字符串前面的空白字符
>Remove leading whitespace if the variable is a string.
#### trim_end
只移除字符串后面的空白字符
>Remove trailing whitespace if the variable is a string.
#### trim_start_matches
如果字符串的前面部分满足给定的模式就移除掉
>Remove leading characters that match the given pattern if the variable is a string.
比如: `{{ value | trim_start_matches(pat="//") }}`
如果value的值是"//a/b/c//"执行的结果就是"a/b/c//".
#### trim_end_matches
如果字符串的后面部分满足给定模式就移除掉
>Remove trailing characters that match the given pattern if the variable is a string.
比如: `{{ value | trim_end_matches(pat="//") }}`
如果value的值是"//a/b/c//"执行结果就是"//a/b/c".
#### truncate
要使用这个过滤器,需要启用`builtins`feature
>Only available if the `builtins` feature is enabled.
按照给定的长度截取字符串,如果字符串的长度还不到给定的长度就原样返回.
>Truncates a string to the indicated length. If the string has a smaller length than
the `length` argument, the string is returned as is.
比如: `{{ value | truncate(length=10) }}`
默认情况下被截取的字符串后面会添加'...',如果不想添加可以指定end参数为空字符串.
>By default, the filter will add an ellipsis at the end if the text was truncated. You can
change the string appended by setting the `end` argument.
比如:`{{ value | truncate(length=10, end="") }}` 输出的字符串后面就没有'...'了
#### striptags
去掉字符中包含的HTML标签。如果提供的字符串不是有效的HTML格式,不保证输出的结果是正常显示的。
Tries to remove HTML tags from input. Does not guarantee well formed output if input is not valid HTML.
比如: `{{ value | striptags}}`
如果value的值是 "<b>Joel</b>"执行的结果就是: "Joel".
*注意*
如果模板本身已经被自动转义过了,你需要先调用`safe`过滤器,所以最好先调用safe过滤器再调用striptags过滤器.
Note that if the template you using it in is automatically escaped, you will need to call the `safe` filter
before `striptags`.
#### first
返回数组中的第一个元素.
如果数组是空的就返回一个空字符串
>Returns the first element of an array.
>If the array is empty, returns empty string.
#### last
返回数组中的最后一个元素.
如果数组是空的就返回空字符串.
>Returns the last element of an array.
>If the array is empty, returns empty string.
#### nth
返回数组中的第n个元素.
如果数组是空的就返回空字符串.
这个过滤器需要个参数n,用于指定元素索引值(从零开始计数)
>Returns the nth element of an array.§
>If the array is empty, returns empty string.
>It takes a required `n` argument, corresponding to the 0-based index you want to get.
例如: `{{ value | nth(n=2) }}`
是返回value中的第3个元素
#### join
使用一个字符串把数组中的元素连起来.
Joins an array with a string.
例如: `{{ value | join(sep=" // ") }}`
如果value的值为`['a', 'b', 'c']`执行结果就是: "a // b // c".
#### length
返回一个数组或者对象或者字符串的长度.
Returns the length of an array, an object, or a string.
#### reverse
返回一个数组的倒排结果.
Returns a reversed string or array.
#### sort
对数组中的元素从小到大排序。
>Sorts an array into ascending order.
**注意**
数组中的元素必须是可排序的:
The values in the array must be a sortable type:
- 数字按照数字大小排序.
- 字符串按照字母顺序排序
- 数组按照长度排序.
- 布尔值false在前true在后
如果要对结构体或者元组进行排序,可以指定按那个属性排序.
>If you need to sort a list of structs or tuples, use the `attribute`
argument to specify which field to sort by.
比如:
比如`people`是包含People的数组
```rust
struct Name(String, String);
struct Person {
name: Name,
age: u32,
}
可以通过指定参数attribute 使用last name进行排序:
The attribute argument can be used to sort by last name:
{{ people | sort(attribute="name.1") }}
也可以指定按年龄排序:
{{ people | sort(attribute="age") }}
删除数组中的重复元素。可以使用attribute参数指定用于去重的属性.对于字符串还可以使用case_sensitive指定是否区分大小写,默认不区分大小写.
Removes duplicate items from an array. The attribute argument can be used to select items based on the values of an inner attribute. For strings, the case_sensitive argument (default is false) can be used to control the comparison.
例如:
比如people是一个包含Person的数组
Given people is an array of Person
struct Name(String, String);
struct Person {
name: Name,
age: u32,
}
可以使用参数 attribute 按年龄对Person去重。
The attribute argument can be used to select one Person for each age:
{{ people | unique(attribute="age") }}
1
或者对last name去重
{{ people | unique(attribute="name.1", case_sensitive="true") }}
Slice an array by the given start and end parameter. Both parameters are
optional and omitting them will return the same array.
Use the start argument to define where to start (inclusive, default to 0)
and end argument to define where to stop (exclusive, default to the length of the array).
start and end are 0-indexed.
{% for i in my_arr | slice(end=5) %}
{% for i in my_arr | slice(start=1) %}
{% for i in my_arr | slice(start=1, end=5) %}
Group an array using the required attribute argument. The filter takes an array and return
a map where the keys are the values of the attribute stringified and the values are all elements of
the initial array having that attribute. Values with missing attribute or where attribute is null
will be discarded.
Example:
Given posts is an array of Post
struct Author {
name: String,
};
struct Post {
content: String,
year: u32,
author: Author,
}
The attribute argument can be used to group posts by year:
{{ posts | group_by(attribute="year") }}
1
or by author name:
{{ posts | group_by(attribute="author.name") }}
Filter the array values, returning only the values where the attribute is equal to the value.
Values with missing attribute or where attribute is null will be discarded.
attribute is mandatory.
Example:
Given posts is an array of Post
struct Author {
name: String,
};
struct Post {
content: String,
year: u32,
author: Author,
draft: bool,
}
The attribute argument can be used to filter posts by draft value:
{{ posts | filter(attribute="draft", value=true) }}
or by author name:
{{ posts | filter(attribute="author.name", value="Vincent") }}
If value is not passed, it will drop any elements where the attribute is null.
Retrieves an attribute from each object in an array. The attribute argument is mandatory and specifies what to extract.
Example:
Given people is an array of Person
struct Name(String, String);
struct Person {
name: Name,
age: u32,
}
The attribute argument is used to retrieve their ages.
{{ people | map(attribute="age") }}
1
Appends values to an array.
{{ posts | concat(with=drafts) }}
1
The filter takes an array and returns a new array with the value(s) from the with parameter
added. If the with parameter is an array, all of its values will be appended one by one to the new array and
not as an array.
This filter can also be used to append a single value to an array if the value passed to with is not an array:
{% set pages_id = pages_id | concat(with=id) %}
The with attribute is mandatory.
Only available if the builtins feature is enabled.
Percent-encodes all the characters in a string which are not included in
unreserved chars(according to RFC3986) with the exception of forward
slash(/).
Example: {{ value | urlencode }}
If value is /foo?a=b&c=d, the output will be /foo%3Fa%3Db%26c%3Dd. / is not escaped.
Only available if the builtins feature is enabled.
Similar to urlencode filter but encodes all non-alphanumeric characters in a string including forward slashes (/).
Example: {{ value | urlencode_strict }}
If value is /foo?a=b&c=d, the output will be %2Ffoo%3Fa%3Db%26c%3Dd. / is
also encoded.
Returns a plural suffix if the value is not equal to ±1, or a singular suffix otherwise. The plural suffix defaults to s and the
singular suffix defaults to the empty string (i.e nothing).
Example: You have {{ num_messages }} message{{ num_messages | pluralize }}
If num_messages is 1, the output will be You have 1 message. If num_messages is 2 the output will be You have 2 messages. You can
also customize the singular and plural suffixes with the singular and plural arguments to the filter:
Example: {{ num_categories }} categor{{ num_categories | pluralize(singular="y", plural="ies") }}
Returns a number rounded following the method given. Default method is common which will round to the nearest integer.
ceil and floor are available as alternative methods.
Another optional argument, precision, is available to select the precision of the rounding. It defaults to 0, which will
round to the nearest integer for the given method.
Example: {{ num | round }} {{ num | round(method="ceil", precision=2) }}
Only available if the builtins feature is enabled.
Returns a human-readable file size (i.e. ‘110 MB’) from an integer.
Example: {{ num | filesizeformat }}
Only available if the builtins feature is enabled.
Parse a timestamp into a date(time) string. Defaults to YYYY-MM-DD format.
Time formatting syntax is inspired from strftime and a full reference is available
on chrono docs.
Example: {{ ts | date }} {{ ts | date(format="%Y-%m-%d %H:%M") }}
If you are using ISO 8601 date strings you can optionally supply a timezone for the date to be rendered in.
Example:
{{ "2019-09-19T13:18:48.731Z" | date(timezone="America/New_York") }}
{{ "2019-09-19T13:18:48.731Z" | date(format="%Y-%m-%d %H:%M", timezone="Asia/Shanghai") }}
Escapes a string’s HTML. Specifically, it makes these replacements:
& is converted to &
< is converted to <
> is converted to >
" (double quote) is converted to "
' (single quote) is converted to '
/ is converted to /
Escapes XML special characters. Specifically, it makes these replacements:
& is converted to &
< is converted to <
> is converted to >
" (double quote) is converted to "
' (single quote) is converted to '
Mark a variable as safe: HTML will not be escaped anymore.
safe only works if it is the last filter of the expression:
{{ content | replace(from="Robert", to="Bob") | safe }} will not be escaped
{{ content | safe | replace(from="Robert", to="Bob") }} will be escaped
Access a value from an object when the key is not a Tera identifier.
Example: {{ sections | get(key="posts/content") }}
Split a string into an array of strings, separated by a pattern given.
Example: {{ path | split(pat="/") }}
Converts a value into an integer. The default argument can be used to specify the value to return on error, and the base argument can be used to specify how to interpret the number. Bases of 2, 8, and 16 understand the prefix 0b, 0o, 0x, respectively.
Converts a value into a float. The default argument can be used to specify the value to return on error.
Transforms any value into a JSON representation. This filter is better used together with safe or when automatic escape is disabled.
Example: {{ value | json_encode() | safe }}
It accepts a parameter pretty (boolean) to print a formatted JSON instead of a one-liner.
Example: {{ value | json_encode(pretty=true) | safe }}
Returns a string representation of the given value.
Example: {{ value | as_str }}
Returns the default value given only if the variable evaluated is not present in the context
and is therefore meant to be at the beginning of a filter chain if there are several filters.
Example: {{ value | default(value=1) }}
This is in most cases a shortcut for:
{% if value %}{{ value }}{% else %}1{% endif %}
However, only the existence of the value in the context is checked. With a value that if would
evaluate to false (such as an empty string, or the number 0), the default filter will not attempt
replace it with the alternate value provided. For example, the following will produce
“I would like to read more !”:
I would like to read more {{ "" | default (value="Louise Michel") }}!
1
If you intend to use the default filter to deal with optional values, you should make sure those values
aren’t set! Otherwise, use a full if block. This is especially relevant for dealing with optional arguments
passed to a macro.
Here are the currently built-in tests:
Returns true if the given variable is defined.
Returns true if the given variable is undefined.
Returns true if the given variable is an odd number.
Returns true if the given variable is an even number.
Returns true if the given variable is a string.
Returns true if the given variable is a number.
Returns true if the given expression is divisible by the arg given.
Example:
{% if rating is divisibleby(2) %}
Divisible
{% endif %}
判断变量是否可以进行遍历(迭代)
Returns true if the given variable can be iterated over in Tera (ie is an array/tuple or an object).
判断一个变量是否是对象
Returns true if the given variable is an object (ie can be iterated over key, value).
Returns true if the given variable is a string starts with the arg given.
Example:
{% if path is starting_with("x/") %}
In section x
{% endif %}
1
2
3
Returns true if the given variable is a string ends with the arg given.
Returns true if the given variable contains the arg given.
The test works on:
strings: is the arg a substring?
arrays: is the arg given one of the member of the array?
maps: is the arg given a key of the map?
Example:
{% if username is containing("xXx") %}
Bad
{% endif %}
Returns true if the given variable is a string and matches the regex in the argument.
Example:
{% if name is matching("^[Qq]ueen") %}
Her Royal Highness, {{ name }}
{% elif name is matching("^[Kk]ing") %}
His Royal Highness, {{ name }}
{% else %}
{{ name }}
{% endif %}
A comprehensive syntax description can be found in the regex crate documentation.
Tera comes with some built-in global functions.
Returns an array of integers created using the arguments given.
There are 3 arguments, all integers:
end: where to stop, mandatory
start: where to start from, defaults to 0
step_by: with what number do we increment, defaults to 1
Only available if the builtins feature is enabled.
Returns the local datetime as string or the timestamp as integer if requested.
There are 2 arguments, both booleans:
timestamp: whether to return the timestamp instead of the datetime
utc: whether to return the UTC datetime instead of the local one
Formatting is not built-in the global function but you can use the date filter like so now() | date(format="%Y") if you
wanted to get the current year.
The template rendering will error with the given message when encountered.
There is only one string argument:
message: the message to display as the error
Only available if the builtins feature is enabled.
Returns a random integer in the given range. There are 2 arguments, both integers:
start: defaults to 0 if not present
end: required
start is inclusive (i.e. can be returned) and end is exclusive.
获取特定名称的环境变量的值。如果获取的环境变量不存在,就会报错,不过也可以设置一个默认值.
Returns the environment variable value for the name given. It will error if the environment variable is not found
but the call can also take a default value instead.
name: 用于指定环境变量名称,必须提供
default: 用于设置默认值
如果环境变量存在就会返回一个字符串类型的值,默认值可以是任何类型。
If the environment variable is found, it will always be a string while your default could be of any type.