unique
删除数组中的重复元素。可以使用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") }}
或者对last name去重
{{ people | unique(attribute="name.1", case_sensitive="true") }}
slice
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_by
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") }}
or by author name:
{{ posts | group_by(attribute="author.name") }}
filter
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.
map
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") }}
concat
Appends values to an array.
{{ posts | concat(with=drafts) }}
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.
urlencode
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.
urlencode_strict
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.
pluralize
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") }}
round
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) }}
filesizeformat
Only available if the builtins feature is enabled.
Returns a human-readable file size (i.e. '110 MB') from an integer.
Example: {{ num | filesizeformat }}
date
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") }}
escape
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 /
escape_xml
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 '
safe
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
get
Access a value from an object when the key is not a Tera identifier.
Example: {{ sections | get(key="posts/content") }}
split
Split a string into an array of strings, separated by a pattern given.
Example: {{ path | split(pat="/") }}
int
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.
float
Converts a value into a float. The default argument can be used to specify the value to return on error.
json_encode
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 }}
as_str
Returns a string representation of the given value.
Example: {{ value | as_str }}
default
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") }}!
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.
Built-in tests
Here are the currently built-in tests:
defined
Returns true if the given variable is defined.
undefined
Returns true if the given variable is undefined.
odd
Returns true if the given variable is an odd number.
even
Returns true if the given variable is an even number.
string
Returns true if the given variable is a string.
number
Returns true if the given variable is a number.
divisibleby
Returns true if the given expression is divisible by the arg given.
Example:
{% if rating is divisibleby(2) %}
Divisible
{% endif %}
iterable
判断变量是否可以进行遍历(迭代)
Returns true if the given variable can be iterated over in Tera (ie is an array/tuple or an object).
object
判断一个变量是否是对象
Returns true if the given variable is an object (ie can be iterated over key, value).
starting_with
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 %}
ending_with
Returns true if the given variable is a string ends with the arg given.
containing
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 %}
matching
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.
Built-in functions
Tera comes with some built-in global functions.
range
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
now
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.
throw
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
get_random
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.
get_env
获取特定名称的环境变量的值。如果获取的环境变量不存在,就会报错,不过也可以设置一个默认值.
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.