百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

Rust模板引擎Tera中文英文对照官方文档-运用

toyiye 2024-06-21 12:37 9 浏览 0 评论

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.

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码