翻译中…
引入Tera
要使用Tera只需要在
1 | tera = "1" |
是不是很简单?
默认情况下, Tera会引入一些依赖比如:
1 2 3 | [dependencies.tera] version = "1" default-features = false |
如果你用的Rust不是2018版本的(你最好使用),你需要在lib.rs或者main.rs文件中写上
And add the following to your
lib.rs ormain.rs if you are not using Rust 2018:
1 | 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.
1 2 3 4 5 6 | templates/ hello.html index.html products/ product.html price.html |
假设这个
Assuming the Rust file is at the same level as the
templates folder, we can get a Tera instance that way:
1 2 3 4 5 6 7 8 9 10 | use tera::Tera; // Use globbing let tera = match Tera::new("templates/**/*.html") { Ok(t) => t, Err(e) => { println!("Parsing error(s): {}", e); ::std::process::exit(1); } }; |
Compiling templates is a step that is meant to only happen once: use something like lazy_static
to define a constant instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 }; } |
You need two things to render a template: a name and a context.
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
The context can either a be data structure that implements the
1 2 3 4 5 6 7 8 9 10 11 12 13 | use 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)?; #[derive(Serialize)] struct Product { name: String } // or a struct tera.render("products/product.html", &Context::from_serialize(&product)?)?; |
Auto-escaping
By default, Tera will auto-escape all content in files ending with
Escaping follows the recommendations from OWASP.
You can override that or completely disable auto-escaping by calling the
1 2 3 4 | // escape only files ending with `.php.html` tera.autoescape_on(vec![".php.html"]); // disable autoescaping completely tera.autoescape_on(vec![]); |
Advanced usage
Extending another instance
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
instance with everything mentioned before:
1 2 3 | let mut tera = Tera::new(&tpl_glob).chain_err(|| "Error parsing templates")?; // ZOLA_TERA is an instance present in a library tera.extend(&ZOLA_TERA)?; |
If anything - templates, filters, etc - with the same name exists in both instances, Tera will only keep yours.
Reloading
If you are watching a directory and want to reload templates on change (editing/adding/removing a template), Tera gives
the
1 | tera.full_reload()?; |
Note that reloading is only available if you are loading templates with a glob.
Loading templates from strings
Tera allows you load templates not only from files but also from plain strings.
1 2 3 4 5 6 7 8 9 10 | // 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 %}"), ])?; |
If some templates are related, for example one extending the other, you will need to the
as Tera will error if it find inconsistencies such as extending a template that Tera doesn’t know about.
Render a one off template
Want to render a single template, for example one coming from a user? The
1 2 3 4 5 | // 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); |
Templates
Introduction
Tera Basics
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{% or{%- and%} or-%} for statements{# and#} for comments
Raw
Tera will consider all text inside the
render what’s inside. Useful if you have text that contains Tera delimiters.
1 2 3 | {% raw %} Hello {{ name }} {% endraw %} |
would be rendered as
Whitespace control
Tera comes with easy to use whitespace control: use
before a statement and
For example, let’s look at the following template:
1 2 | {% set my_var = 2 %} {{ my_var }} |
will have the following output:
1 | 2 |
If we want to get rid of the empty line, we can write the following:
1 2 | {% set my_var = 2 -%} {{ my_var }} |
Comments
To comment out part of the template, wrap it in
will not be rendered.
1 | {# A comment #} |
Data structures
Literals
Tera has a few literals that can be used:
- booleans:
true andfalse - integers
- floats
- strings: text delimited by
"" ,'' or backticks - arrays: a list of literals and/or idents by
[ and] and comma separated (trailing comma allowed)
Variables
Variables are defined by the context given when rendering a template. If you’d like to define your own variables, see the Assignments section.
You can render a variable by using the
Trying to access or render a variable that doesn’t exist will result in an error.
A magical variable is available in every template if you want to print the current context:
Dot notation:
Construct and attributes can be accessed by using the dot (
Specific members of an array or tuple are accessed by using the
Square bracket notation:
A more powerful alternative to (
Variables can be rendering using the notation
If the item is not in quotes it will be treated as a variable.
Assuming you have the following objects in your context
and
Only variables evaluating to String and Number can be used as index: anything else will be
an error.
Expressions
Tera allows expressions almost everywhere.
Math
You can do some basic math in Tera but it shouldn’t be abused other than the occasional
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:
+ : adds 2 values together,{{ 1 + 1 }} will print2 - : performs a substraction,{{ 2 - 1 }} will print1 / : performs a division,{{ 10 / 2 }} will print5 * : performs a multiplication,{{ 5 * 2 }} will print10 % : performs a modulo,{{ 2 % 2 }} will print0
The priority of operations is the following, from lowest to highest:
+ and- * and/ and%
Comparisons
== : checks whether the values are equal!= : checks whether the values are different>= : true if the left value is equal or greater to the right one<= : true if the right value is equal or greater to the left one> : true if the left value is greater than the right one< : true if the right value is greater than the left one
Logic
and : true if the left and right operands are trueor : true if the left or right operands are truenot : negate a statement
String concatenation
You can concatenate several strings/idents using the
1 2 3 4 5 | {{ "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 checking
You can check whether a left side is contained in a right side using the
1 2 3 4 5 | {{ some_var in [1, 2, 3] }} {{ 'index' in page.path }} {{ an_ident not in an_obj }} |
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.
Manipulating data
Assignments
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.
1 2 3 4 5 6 | {% 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] %} |
If you want to assign a value in the global context while in a for loop, you can use
1 2 3 4 5 6 | {% 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] %} |
Outside of a for loop,
Filters
You can modify variables using filters.
Filters are separated from the variable by a pipe symbol (
Multiple filters can be chained: the output of one filter is applied to the next.
For example,
It is equivalent to
Calling filters on a incorrect type like trying to capitalize an array or using invalid types for arguments will result in a error.
Filters are functions with the
1 | 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 2 3 4 5 6 | {{ 1 + a | length }} // is equal to {{ (1 + a) | length } // this will probably error // This will do what you wanted initially {{ a | length + 1 }} |
Tera has many built-in filters that you can use.
Filter sections
Whole sections can also be processed by filters if they are encapsulated in
tags where
1 2 3 | {% filter upper %} Hello {% endfilter %} |
This example transforms the text
Filter sections can also contain
1 2 3 4 5 | {% filter upper %} {% block content_to_be_upper_cased %} This will be upper-cased {% endblock content_to_be_upper_cased %} {% endfilter %} |
Tests
Tests can be used against an expression to check some condition on it and
are made in
For example, you would write the following to test if an expression is odd:
1 2 3 | {% if my_number is odd %} Odd {% endif %} |
Tests can also be negated:
1 2 3 | {% if my_number is not odd %} Even {% endif %} |
Tests are functions with the
1 | tera.register_tester("odd", testers::odd); |
Tera has many built-in tests that you can use.
Functions
Functions are Rust code that return a
Quite often, functions will need to capture some external variables, such as a
the list of URLs for example.
To make that work, the type of
Here’s an example on how to implement a very basic function:
1 2 3 4 5 6 7 8 9 10 11 | 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()), } }) } |
You then need to add it to Tera:
1 | tera.register_function("url_for", make_url_for(urls)); |
And you can now call it from a template:
1 | {{/* url_for(name="home") */}} |
Currently functions can be called in two places in templates:
- variable block:
{{/* url_for(name="home") */}} - for loop container:
{% for i in range(end=5) %}
Tera comes with some built-in functions.
Control structures
If
Conditionals are fully supported and are identical to the ones in Python.
1 2 3 4 5 6 7 | {% 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:
1 2 3 4 5 | {% if my_var %} {{ my_var }} {% else %} Sorry, my_var isn't defined. {% endif %} |
Every
For
Loop over items in a array:
1 2 3 | {% for product in products %} {{loop.index}}. {{product.name}} {% endfor %} |
A few special variables are available inside for loops:
loop.index : current iteration 1-indexedloop.index0 : current iteration 0-indexedloop.first : whether this is the first iterationloop.last : whether this is the last iteration
Every
You can also loop on maps and structs using the following syntax:
1 2 3 | {% for key, value in products %} {{loop.index}}. {{product.name}} {% endfor %} |
If you are iterating on an array, you can also apply filters to the container:
1 2 3 | {% for product in products | reverse %} {{loop.index}}. {{product.name}} {% endfor %} |
You can also iterate on array literals:
1 2 3 | {% for a in [1,2,3,] %} {{a}} {% endfor %} |
Lastly, you can set a default body to be rendered when the container is empty:
1 2 3 4 5 | {% for product in products %} {{loop.index}}. {{product.name}} {% else %} No products. {% endfor %} |
Loop Controls
Within a loop,
To stop iterating when
1 2 3 4 | {% for product in products %} {% if product.id == target_id %}{% break %}{% endif %} {{loop.index}}. {{product.name}} {% endfor %} |
To skip even-numbered items:
1 2 3 4 | {% 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
1 | {% include "included.html" %} |
Tera doesn’t offer passing a custom context to the
If you want to do that, use macros.
While you can
them: the template calling
Macros
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:
1 2 3 4 5 6 | {% 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:
1 | {% import "macros.html" as macros %} |
You can name that file namespace (
A macro is called like this:
1 2 | // namespace::macro_name(**kwargs) {{ macros::input(label="Name", type="text") }} |
Do note that macros, like filters, require keyword arguments.
If you are trying to call a macro defined in the same file or itself, you will need to use the
The
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:
1 2 3 | {% macro factorial(n) %} {% if n > 1 %}{{ n }} - {{ self::factorial(n=n-1) }}{% else %}1{% endif %} {% endmacro factorial %} |
Macros body can contain all normal Tera syntax with the exception of macros definition,
Inheritance
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.
There can be multiple levels of inheritance (i.e. A extends B that extends C).
Base template
A base template typically contains the basic document structure as well as
several
For example, here’s a
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!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> |
The only difference with Jinja2 being that the
This
The
Child template
Again, straight from Jinja2 docs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | {% 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 %} |
To indicate inheritance, you have use the
to extend.
The
Nested blocks also work in Tera. Consider the following templates:
1 2 3 4 5 6 7 8 9 10 11 | // 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 %} |
The block
- Find the first base template:
grandparent - See
hey block in it and checks if it is inchild andparent template - It is in
child so we render it, it contains asuper() call so we render thehey block fromparent ,
which also contains asuper() so we render thehey block of thegrandparent template as well - See
ending block inchild , render it and also renders theending block ofparent as there is asuper()
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 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
Takes 2 mandatory string named arguments:
the
Example:
addslashes
Adds slashes before quotes.
Example:
If value is “I’m using Tera”, the output will be “I\'m using Tera”.
slugify
Only available if the
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.
Example:
If value is "-Hello world! ", the output will be “hello-world”.
title
Capitalizes each word inside a sentence.
Example:
If value is “foo bar”, the output will be “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.
Example:
If value is “//a/b/c//”, the output will be “a/b/c//”.
trim_end_matches
Remove trailing characters that match the given pattern if the variable is a string.
Example:
If value is “//a/b/c//”, the output will be “//a/b/c”.
truncate
Only available if the
Truncates a string to the indicated length. If the string has a smaller length than
the
Example:
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
For example,
striptags
Tries to remove HTML tags from input. Does not guarantee well formed output if input is not valid HTML.
Example:
If value is “Joel”, the output will be “Joel”.
Note that if the template you using it in is automatically escaped, you will need to call the
before
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
Returns the nth element of an array.§
If the array is empty, returns empty string.
It takes a required
Example:
join
Joins an array with a string.
Example:
If value is the array
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:
- numbers are sorted by their numerical value.
- strings are sorted in alphabetical order.
- arrays are sorted by their length.
- bools are sorted as if false=0 and true=1
If you need to sort a list of structs or tuples, use the
argument to specify which field to sort by.
Example:
Given
1 2 3 4 5 6 | struct Name(String, String); struct Person { name: Name, age: u32, } |
The
1 | {{ people | sort(attribute="name.1") }} |
or by age:
1 | {{ people | sort(attribute="age") }} |
unique
Removes duplicate items from an array. The
Example:
Given
1 2 3 4 5 6 | struct Name(String, String); struct Person { name: Name, age: u32, } |
The
1 | {{ people | unique(attribute="age") }} |
or by last name:
1 | {{ people | unique(attribute="name.1", case_sensitive="true") }} |
slice
Slice an array by the given
optional and omitting them will return the same array.
Use the
and
1 2 3 | {% 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
a map where the keys are the values of the
the initial array having that
will be discarded.
Example:
Given
1 2 3 4 5 6 7 8 9 | struct Author { name: String, }; struct Post { content: String, year: u32, author: Author, } |
The
1 | {{ posts | group_by(attribute="year") }} |
or by author name:
1 | {{ posts | group_by(attribute="author.name") }} |
filter
Filter the array values, returning only the values where the
Values with missing
Example:
Given
1 2 3 4 5 6 7 8 9 10 | struct Author { name: String, }; struct Post { content: String, year: u32, author: Author, draft: bool, } |
The
1 | {{ posts | filter(attribute="draft", value=true) }} |
or by author name:
1 | {{ posts | filter(attribute="author.name", value="Vincent") }} |
If
map
Retrieves an attribute from each object in an array. The
Example:
Given
1 2 3 4 5 6 | struct Name(String, String); struct Person { name: Name, age: u32, } |
The
1 | {{ people | map(attribute="age") }} |
concat
Appends values to an array.
1 | {{ posts | concat(with=drafts) }} |
The filter takes an array and returns a new array with the value(s) from the
added. If the
not as an array.
This filter can also be used to append a single value to an array if the value passed to
1 | {% set pages_id = pages_id | concat(with=id) %} |
The
urlencode
Only available if the
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:
If value is
urlencode_strict
Only available if the
Similar to
Example:
If value 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
singular suffix defaults to the empty string (i.e nothing).
Example:
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
Example:
round
Returns a number rounded following the method given. Default method is
Another optional argument,
round to the nearest integer for the given method.
Example:
filesizeformat
Only available if the
Returns a human-readable file size (i.e. ‘110 MB’) from an integer.
Example:
date
Only available if the
Parse a timestamp into a date(time) string. Defaults to
Time formatting syntax is inspired from strftime and a full reference is available
on chrono docs.
Example:
If you are using ISO 8601 date strings you can optionally supply a timezone for the date to be rendered in.
Example:
1 2 3 | {{ "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.
{{ 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:
split
Split a string into an array of strings, separated by a pattern given.
Example:
int
Converts a value into an integer. The
float
Converts a value into a float. The
json_encode
Transforms any value into a JSON representation. This filter is better used together with
Example:
It accepts a parameter
Example:
as_str
Returns a string representation of the given value.
Example:
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:
This is in most cases a shortcut for:
1 | {% if value %}{{ value }}{% else %}1{% endif %} |
However, only the existence of the value in the context is checked. With a value that
evaluate to false (such as an empty string, or the number 0), the
replace it with the alternate value provided. For example, the following will produce
“I would like to read more !”:
1 | 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
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:
1 2 3 | {% 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:
1 2 3 | {% 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:
1 2 3 | {% 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:
1 2 3 4 5 6 7 | {% 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, mandatorystart : where to start from, defaults to0 step_by : with what number do we increment, defaults to1
now
Only available if the
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 datetimeutc : whether to return the UTC datetime instead of the local one
Formatting is not built-in the global function but you can use the
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
Returns a random integer in the given range. There are 2 arguments, both integers:
start : defaults to 0 if not presentend : required
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 : the name of the environment variable to look for, requireddefault : a default value in case the environment variable is not found
If the environment variable is found, it will always be a string while your default could be of any type.