Askama
Askama implements a template rendering engine based on Jinja.
It generates Rust code from your templates at compile time
based on a user-defined struct to hold the template’s context.
See below for an example.
All feedback welcome! Feel free to file bugs, requests for documentation and any other feedback to the issue tracker.
Have a look at our Askama Playground, if you want to try out askama’s code generation online.
Feature highlights
- Construct templates using a familiar, easy-to-use syntax
- Benefit from the safety provided by Rust’s type system
- Template code is compiled into your crate for optimal performance
- Debugging features to assist you in template development
- Templates must be valid UTF-8 and produce UTF-8 when rendered
- Works on stable Rust
Supported in templates
- Template inheritance
- Loops, if/else statements and include support
- Macro support
- Variables (no mutability allowed)
- Many built-in filters, and the ability to use your own
- Whitespace suppressing with ‘-’ markers
- Opt-out HTML escaping
- Syntax customization
Getting Started
First, add the following to your crate’s Cargo.toml:
# in [dependencies] section
askama = "0.14.0"
Now create a directory called templates in your crate root.
In it, create a file called hello.html, containing the following:
Hello, {{ name }}!
In any Rust file inside your crate, add the following:
use askama::Template; // bring trait in scope
#[derive(Template)] // this will generate the code...
#[template(path = "hello.html")] // using the template in this path, relative
// to the `templates` dir in the crate root
struct HelloTemplate<'a> { // the name of the struct can be anything
name: &'a str, // the field name should match the variable name
// in your template
}
fn main() {
let hello = HelloTemplate { name: "world" }; // instantiate your struct
println!("{}", hello.render().unwrap()); // then render it.
}
You should now be able to compile and run this code.
Creating Templates
An Askama template is a struct definition which provides the template
context combined with a UTF-8 encoded text file (or inline source, see
below). Askama can be used to generate any kind of text-based format.
The template file’s extension may be used to provide content type hints.
A template consists of text contents, which are passed through as-is, expressions, which get replaced with content while being rendered, and tags, which control the template’s logic. The template syntax is very similar to Jinja, as well as Jinja-derivatives like Twig or Tera.
#[derive(Template)] // this will generate the code...
#[template(path = "hello.html")] // using the template in this path, relative
// to the `templates` dir in the crate root
struct HelloTemplate<'a> { // the name of the struct can be anything
name: &'a str, // the field name should match the variable name
// in your template
}
The template() attribute
Askama works by generating one or more trait implementations for any
struct type decorated with the #[derive(Template)] attribute. The
code generation process takes some options that can be specified through
the template() attribute. The following sub-attributes are currently
recognized:
-
path(e.g.
path = "foo.html"): sets the path to the template file. The path is interpreted as relative to the configured template directories (by default, this is atemplatesdirectory next to yourCargo.toml). The file name extension is used to infer an escape mode (see below). In web framework integrations, the path’s extension may also be used to infer the content type of the resulting response. Cannot be used together withsource.#[derive(Template)] #[template(path = "hello.html")] struct HelloTemplate<'a> { ... } -
source(e.g.
source = "{{ foo }}"): directly sets the template source. This can be useful for test cases or short templates. The generated path is undefined, which generally makes it impossible to refer to this template from other templates. Ifsourceis specified,extmust also be specified (see below). Cannot be used together withpath.#[derive(Template)] #[template(source = "Hello {{ name }}")] struct HelloTemplate<'a> { name: &'a str, } -
in_doc(e.g.
in_doc = true): please see the section “documentation as template code”. -
ext(e.g.
ext = "txt"): lets you specify the content type as a file extension. This is used to infer an escape mode (see below), and some web framework integrations use it to determine the content type. Cannot be used together withpath.#[derive(Template)] #[template(source = "Hello {{ name }}", ext = "txt")] struct HelloTemplate<'a> { name: &'a str, } -
print(e.g.
print = "code"): enable debugging by printing nothing (none), the parsed syntax tree (ast), the generated code (code) orallfor both. The requested data will be printed to stdout at compile time.#[derive(Template)] #[template(path = "hello.html", print = "all")] struct HelloTemplate<'a> { ... } -
block(e.g.
block = "block_name"): renders the block by itself. Expressions outside of the block are not required by the struct, and inheritance is also supported. This can be useful when you need to decompose your template for partial rendering, without needing to extract the partial into a separate template or macro.#[derive(Template)] #[template(path = "hello.html", block = "hello")] struct HelloTemplate<'a> { ... } -
blocks(e.g.
blocks = ["title", "content"]): automatically generates (a number of) sub-templates that act as if they had ablock = "..."attribute. You can access the sub-templates with the methodmy_template.as_block_name(), whereblock_nameis the name of the block:#[derive(Template)] #[template( ext = "txt", source = " {% block title %} ... {% endblock %} {% block content %} ... {% endblock %} ", blocks = ["title", "content"] )] struct News<'a> { title: &'a str, message: &'a str, } let news = News { title: "Announcing Rust 1.84.1", message: "The Rust team has published a new point release of Rust, 1.84.1.", }; assert_eq!( news.as_title().render().unwrap(), "<h1>Announcing Rust 1.84.1</h1>" ); -
escape(e.g.
escape = "none"): override the template’s extension used for the purpose of determining the escaper for this template. See the section on configuring custom escapers for more information.#[derive(Template)] #[template(path = "hello.html", escape = "none")] struct HelloTemplate<'a> { ... } -
syntax(e.g.
syntax = "foo"): set the syntax name for a parser defined in the configuration file. The default syntax , “default”, is the one provided by Askama.#[derive(Template)] #[template(path = "hello.html", syntax = "foo")] struct HelloTemplate<'a> { ... } -
config(e.g.
config = "config_file_path"): set the path for the config file to be used. The path is interpreted as relative to your crate root.#[derive(Template)] #[template(path = "hello.html", config = "config.toml")] struct HelloTemplate<'a> { ... } -
askama(e.g.
askama = askama): if you are using askama in a subproject, a library or a macro, it might be necessary to specify the path where to find the moduleaskama:#[doc(hidden)] use askama as __askama; #[macro_export] macro_rules! new_greeter { ($name:ident) => { #[derive(Debug, $crate::askama::Template)] #[template( ext = "txt", source = "Hello, world!", askama = $crate::__askama )] struct $name; } } new_greeter!(HelloWorld); assert_eq!(HelloWorld.to_string(), Ok("Hello, world."));
Templating enums
You can add derive Templates for structs and enums.
If you add #[template()] only to the item itself, both item kinds work exactly the same.
But with enums you also have the option to add a specialized implementation to one, some,
or all variants:
#[derive(Debug, Template)]
#[template(path = "area.txt")]
enum Area {
Square(f32),
Rectangle { a: f32, b: f32 },
Circle { radius: f32 },
}
{%- match self -%}
{%- when Self::Square(side) -%}
{{side}}^2
{%- when Self::Rectangle { a, b} -%}
{{a}} * {{b}}
{%- when Self::Circle { radius } -%}
pi * {{radius}}^2
{%- endmatch -%}
will give you the same results as:
#[derive(Template, Debug)]
#[template(ext = "txt")]
enum AreaPerVariant {
#[template(source = "{{self.0}}^2")]
Square(f32),
#[template(source = "{{a}} * {{b}}")]
Rectangle { a: f32, b: f32 },
#[template(source = "pi * {{radius}}^2")]
Circle { radius: f32 },
}
As you can see with the ext attribute, enum variants inherit most settings of the enum:
config, escape, ext, syntax, and whitespace.
Not inherited are: block, and print.
If there is no #[template] annotation for an enum variant,
then the enum needs a default implementation, which will be used if self is this variant.
A good compromise between annotating only the template, or all its variants,
might be using the block argument on the members:
#[derive(Template, Debug)]
#[template(path = "area.txt")]
enum AreaWithBlocks {
#[template(block = "square")]
Square(f32),
#[template(block = "rectangle")]
Rectangle { a: f32, b: f32 },
#[template(block = "circle")]
Circle { radius: f32 },
}
{%- block square -%}
{{self.0}}^2
{%- endblock -%}
{%- block rectangle -%}
{{a}} * {{b}}
{%- endblock -%}
{%- block circle -%}
pi * {{radius}}^2
{%- endblock -%}
Documentation as template code
As an alternative to supplying the code template code in an external file (e.g. path argument),
or as a string (e.g. source argument), you can also enable the "code-in-doc" feature.
With this feature, you can specify the template code directly in the documentation
of the template item.
Instead of path = "…" or source = "…", specify in_doc = true in the #[template] attribute,
and in the item’s documentation, add a code block with the askama attribute:
/// Here you can put our usual comments.
///
/// ```askama
/// <div>{{ lines|linebreaksbr }}</div>
/// ```
///
/// Any usual docs, including tests can be put in here, too:
///
/// ```rust
/// assert_eq!(
/// Example { lines: "a\nb\nc" }.to_string(),
/// "<div>a<br/>b<br/>c</div>"
/// );
/// ```
///
/// All comments are still optional, though.
#[derive(Template)]
#[template(ext = "html", in_doc = true)]
struct Example<'a> {
lines: &'a str,
}
If you want to supply the template code in the comments,
then you have to specify the ext argument, too, e.g. #[template(ext = "html")].
Instead of askama, you can also write jinja or jinja2,
e.g. to get it to work better in conjunction with syntax highlighters.
Runtime values
It is possible to define variables at runtime and to use them in the templates using the values
filter or the askama::get_value function and to call the _with_values variants of the render
methods. It expects an extra argument implementing the Values trait. This trait is implemented on
a few types provided by the std, like HashMap:
use std::collections::HashMap;
let mut values: HashMap<&str, Box<dyn Any>> = HashMap::new();
// We add a new value named "name" with the value "Bibop".
values.insert("name", Box::new("Bibop"));
values.insert("age", Box::new(12u32));
The Values trait is expecting types storing data with the Any trait, allowing to store any type.
Then to render with these values:
template_struct.render_with_values(&values).unwrap();
There are two ways to get the values from the template, either by using the value filter
or by calling directly the askama::get_value function:
{% if let Ok(name) = "name"|value::<&str> %}
name is {{ name }}
{% endif %}
{% if let Ok(age) = askama::get_value::<u32>("age") %}
age is {{ age }}
{% endif %}
If you try to retrieve a value with the wrong type or that you didn’t set, you will get an
Err(askama::Error::ValueType) or a Err(askama::Error::ValueMissing).
Another example with a key-value tuple:
let value = "value".to_string();
let tuple: (&str, &dyn Any) = ("a", &value);
template_struct.render_with_values(&tuple).unwrap();
With this setup, only the "a" key will return a value:
{% if let Ok(name) = "a"|value::<String> %}
a is {{ a }}
{% endif %}
Debugging and Troubleshooting
You can view the parse tree for a template as well as the generated code by
changing the template attribute item list for the template struct:
#[derive(Template)]
#[template(path = "hello.html", print = "all")]
struct HelloTemplate<'a> { ... }
The print key can take one of four values:
none(the default value)ast(print the parse tree)code(print the generated code)all(print both parse tree and code)
The resulting output will be printed to stderr during the compilation process.
The parse tree looks like this for the example template:
[Lit("", "Hello,", " "), Expr(WS(false, false), Var("name")), Lit("", "!", "\n")]
The generated code looks like this:
impl<'a> askama::Template for HelloWorld<'a> {
fn render_into<AskamaW>(&self, __askama_writer: &mut AskamaW) -> askama::Result<()>
where
AskamaW: core::fmt::Write + ?Sized,
{
__askama_writer.write_str("Hello, ")?;
match (
&((&&askama::filters::AutoEscaper::new(
&(self.name),
askama::filters::Html,
))
.askama_auto_escape()?),
) {
(expr2,) => {
(&&askama::filters::Writable(expr2)).askama_write(__askama_writer)?;
}
}
__askama_writer.write_str("!")?;
Ok(())
}
const SIZE_HINT: usize = 11usize;
}
Configuration
At compile time, Askama will read optional configuration values from
askama.toml in the crate root (the directory where Cargo.toml can
be found) if the config feature is enabled (it’s enabled by default).
Currently, this covers the directories to search for templates, custom
syntax configuration and escaper configuration.
This example file demonstrates the default configuration:
[general]
# Directories to search for templates, relative to the crate root.
dirs = ["templates"]
# Unless you add a `-` in a block, whitespace characters won't be trimmed.
whitespace = "preserve"
Please note that dirs support glob (*) syntax. So you can write:
[general]
dirs = ["templates/*"]
Or even:
[general]
dirs = ["templates/**"]
If you want to include sub-folders.
Whitespace control
In the default configuration, you can use the - operator to indicate that
whitespace should be suppressed before or after a block. For example:
<div>
{%- if something %}
Hello
{% endif %}
In the template above, only the whitespace between <div> and {%- will be
suppressed. If you set whitespace to "suppress":
[general]
whitespace = "suppress"
Then whitespace characters before and after each block will be suppressed by default.
To preserve the whitespace characters, you can use the + operator:
{% if something +%}
Hello
{%+ endif %}
In this example, Hello will be surrounded with newline characters.
There is a third possibility: in case you want to suppress all whitespace
characters except one, you can use ~:
{% if something ~%}
Hello
{%~ endif %}
To be noted, if one of the trimmed characters is a newline, then the only character remaining will be a newline.
If you want this to be the default behavior, you can set whitespace to
"minimize":
[general]
whitespace = "minimize"
To be noted: you can also configure whitespace directly into the template
derive proc macro:
#[derive(Template)]
#[template(whitespace = "suppress")]
pub struct SomeTemplate;
If you configure whitespace directly into the template derive proc-macro,
it will take precedence over the one in your configuration file. So in this
case, if you already set whitespace = "minimize" into your configuration file,
it will be replaced by suppress for this template.
Custom syntaxes
Here is an example that defines two custom syntaxes:
[general]
default_syntax = "foo"
[[syntax]]
name = "foo"
block_start = "%{"
comment_start = "#{"
expr_end = "^^"
[[syntax]]
name = "bar"
block_start = "%%"
block_end = "%%"
comment_start = "%#"
expr_start = "%{"
A syntax block consists of at least the attribute name which uniquely
names this syntax in the project.
The following keys can currently be used to customize template syntax:
block_start, defaults to{%block_end, defaults to%}comment_start, defaults to{#comment_end, defaults to#}expr_start, defaults to{{expr_end, defaults to}}
Values must be at least two characters long. If a key is omitted, the value from the default syntax is used.
Escapers
Here is an example of a custom escaper:
[[escaper]]
path = "::tex_escape::Tex"
extensions = ["tex"]
An escaper block consists of the attributes path and extensions. path
contains a Rust identifier that must be in scope for templates using this
escaper. This type must implement the Escaper
trait.
extensions defines a list of file extensions that will trigger
the use of that escaper. Extensions are matched in order, starting with the
first escaper configured and ending with the default escapers for HTML
(extensions html, htm, xml, j2, jinja, jinja2) and plain text
(no escaping; md, yml, none, txt, and the empty string). Note that
this means you can also define other escapers that match different extensions
to the same escaper.
You can then use templates with this extension or use the
escape filter with
the name of your extension in your template:
{{ some_string|escape("tex") }}
As an example, we want .js files to be treated like “txt” files. To do so:
[[escaper]]
path = "askama::filters::Text"
extensions = ["js"]
Text implements the
Escaper trait so since we don’t need want any escaping on our .js files, we use
it.
You can take a look at the custom escaper example in the askama repository.
Template Syntax
Syntax overview
| Syntax | Description |
|---|---|
{{ ... }} | Expression to be evaluated, escaped and printed |
{{ ... | ... }} | Expression with filter(s) |
{% filter ... %} ... {% endfilter %} | Filter block |
{# ... #} | Comment |
{% let ... = ... %} or {% set ... = ... %} | Variable assignment |
{% decl ... %} or {% declare ... = ... %} | Set variable values later |
{% if ... %} ... {% else if ... %} ... {% else %} ... {% endif %} | If-Else conditional block |
{% match ... %} {% when ... %} ... {% else %} ... {% endmatch %} | Match block |
{% for ... in ... %} ... {% else %} ... {% endfor %} | For loop block |
{% continue %} | Continue to next iteration of loop |
{% break %} | Break out of loop |
{% include "..." %} | Include another template |
{% extends "..." %} | Template inheritance |
{% block ... %} ... {% endblock %} | Block definition for inheritance |
{% macro ...(...) %} ... {% endmacro %} | Macro definition |
{{ ...(...) }} | Macro invocation |
{% call ...(...) %}{% endcall %} | Macro call block |
{% import "..." as ... %} | Import macros from another template |
{% raw %} ... {% endraw %} | Raw block - prints contents as-is (without templating) |
Variables
Top-level template variables are defined by the template’s context type.
You can use a dot (.) to access variable’s attributes or methods.
Reading from variables is subject to the usual borrowing policies.
For example, {{ name }} will get the name field from the template
context,
while {{ user.name }} will get the name field of the user
field from the template context.
Using constants in templates
You can use constants defined in your Rust code. For example if you have:
pub const MAX_NB_USERS: usize = 2;
defined in your crate root, you can then use it in your templates by
using crate::MAX_NB_USERS:
<p>The user limit is {{ crate::MAX_NB_USERS }}.</p>
{% set value = 4 %}
{% if value > crate::MAX_NB_USERS %}
<p>{{ value }} is bigger than MAX_NB_USERS.</p>
{% else %}
<p>{{ value }} is less than MAX_NB_USERS.</p>
{% endif %}
Assignments
Inside code blocks, you can also declare variables or assign values to variables. Assignments can’t be imported by other templates.
Assignments use the let tag:
{% let name = user.name %}
{% let len = name.len() %}
Like Rust, Askama also supports shadowing variables.
{% let foo = "bar" %}
{{ foo }}
{% let foo = "baz" %}
{{ foo }}
You can declare variables as mutable with the mut keyword:
{# In this example, `foo` is an iterator. If you want to be able to iterate it,
you need it to be mutable #}
{% let mut foo = [1, 2].iter() %}
{{ foo.next().unwrap() }}
For compatibility with Jinja, set can be used in place of let.
Let/set blocks
You can create a variable and initialize it with a block computed string:
{% let x %}
{{ crate::some_function() }} = {{ a * b}}
{% endlet %}
Set variable values later
If you want to create a variable but set its value based on a condition, you can
declare it without a value by using the decl (or declare) keyword:
{% decl val -%}
{% if len == 0 -%}
{% let val = "foo" -%}
{% else -%}
{% let val = name -%}
{% endif -%}
{{ val }}
Borrow rules
In some cases, the value of a variable initialization will be put behind a reference to prevent changing ownership. The rules are as follows:
- If the value is an expression of more than one element (like
x + 2), it WILL NOT BE put behind a reference. - If the value is a variable defined in the templates, it WILL NOT BE put behind a reference.
- If the value has a filter applied to it (
x|capitalize), it WILL NOT BE put behind a reference. - If the value is a field (
x.y), it WILL BE put behind a reference. - If the expression ends with a question mark (like
x?), it WILL NOT BE put behind a reference.
Compound assignments
Using the keyword mut, compound assignments (also called
“augmented assignments”), such as x += 1 to increment x by 1, are possible, too:
{%- let mut counter = 0 -%}
{%- for i in 1..=10 -%}
{%- mut counter += i -%}
{{ counter }}
{% endfor -%}
This example will output 1 3 6 10 15….
The target can be a variable or a more complex expression. The rules are the same as in rust, e.g. the left-hand side of the expression, i.e. the assignment target, must be mutable. All compound assignment operators that are valid in rust are valid in askama, too.
Filters
Values such as those obtained from variables can be post-processed
using filters.
Filters are applied to values using the pipe symbol (|) and may
have optional extra arguments in parentheses.
Filters can be chained, in which case the output from one filter
is passed to the next.
For example, {{ "{:?}"|format(name|escape) }} will escape HTML
characters from the value obtained by accessing the name field,
and print the resulting string as a Rust literal.
The built-in filters are documented as part of the filters documentation.
To define your own filters, simply have a module named filters in
scope of the context deriving a Template impl. Note that in case of
name collision, the built in filters take precedence.
Filter blocks
You can apply a filter on a whole block at once using filter blocks:
{% filter lower %}
{{ t }} / HELLO / {{ u }}
{% endfilter %}
The lower filter will be applied on the whole content.
Just like filters, you can combine them:
{% filter lower|capitalize %}
{{ t }} / HELLO / {{ u }}
{% endfilter %}
In this case, lower will be called and then capitalize will be
called on what lower returned.
Whitespace control
Askama considers all tabs, spaces, newlines and carriage returns to be whitespace. By default, it preserves all whitespace in template code, except that a single trailing newline character is suppressed. However, whitespace before and after expression and block delimiters can be suppressed by writing a minus sign directly following a start delimiter or leading into an end delimiter.
Here is an example:
{% if foo %}
{{- bar -}}
{% else if another -%}
nothing
{%- endif %}
This discards all whitespace inside the if/else block. If a literal
(any part of the template not surrounded by {% %} or {{ }})
includes only whitespace, whitespace suppression on either side will
completely suppress that literal content.
If the whitespace default control is set to “suppress” and you want
to preserve whitespace characters on one side of a block or of an
expression, you need to use +. Example:
<a href="/" {#+ #}
class="something">text</a>
In the above example, one whitespace character is kept
between the href and the class attributes.
There is a third possibility. In case you want to suppress all whitespace
characters except one ("minimize"), you can use ~:
{% if something ~%}
Hello
{%~ endif %}
To be noted, if one of the trimmed characters is a newline, then the only character remaining will be a newline.
Whitespace controls can also be defined by a configuration file or in the derive macro. These definitions follow the global-to-local preference:
- Inline (
-,+,~) - Derive (
#[template(whitespace = "suppress")]) - Configuration (in
askama.toml,whitespace = "preserve")
Two inline whitespace controls may point to the same whitespace span. In this case, they are resolved by the following preference.
- Suppress (
-) - Minimize (
~) - Preserve (
+)
Functions
There are several ways that functions can be called within templates, depending on where the function definition resides. These are:
- Template
structfields - Static functions
- Struct/Trait implementations
Template struct field
When the function is a field of the template struct, we can simply call it
by invoking the name of the field, followed by parentheses containing any
required arguments. For example, we can invoke the function foo for the
following MyTemplate struct:
#[derive(Template)]
#[template(source = "{{ foo(123) }}", ext = "txt")]
struct MyTemplate {
foo: fn(u32) -> String,
}
However, since we’ll need to define this function every time we create an
instance of MyTemplate, it’s probably not the most ideal way to associate
some behavior for our template.
Static functions
When a function exists within the same Rust module as the template
definition, we can invoke it using the self path prefix, where self
represents the scope of the module in which the template struct resides.
For example, here we call the function foo by writing self::foo(123)
within the MyTemplate struct source:
fn foo(val: u32) -> String {
format!("{}", val)
}
#[derive(Template)]
#[template(source = "{{ self::foo(123) }}", ext = "txt")]
struct MyTemplate;
This has the advantage of being able to share functionality across multiple templates, without needing to expose the function publicly outside of its module.
However, we are not limited to local functions defined within the same module. We can call any public function by specifying the full path to that function within the template source. For example, given a utilities module such as:
// src/templates/utils/mod.rs
pub fn foo(val: u32) -> String {
format!("{}", val)
}
Within our MyTemplate source, we can call the foo function by writing:
// src/templates/my_template.rs
#[derive(Template)]
#[template(source = "{{ crate::templates::utils::foo(123) }}", ext = "txt")]
struct MyTemplate;
Struct / trait implementations
Finally, we can call methods of our template struct:
#[derive(Template)]
#[template(source = "{{ foo(123) }}", ext = "txt")]
struct MyTemplate {
count: u32,
};
impl MyTemplate {
fn foo(&self, val: u32) -> String {
format!("{} is the count, {} is the value", self.count, val)
}
}
You can also use self.foo(123), or even Self::foo(self, 123), as you see
fit.
Similarly, using the Self path, we can also call any method belonging
to a trait that has been implemented for our template struct:
trait Hello {
fn greet(name: &str) -> String;
}
#[derive(Template)]
#[template(source = r#"{{ Self::greet("world") }}"#, ext = "txt")]
struct MyTemplate;
impl Hello for MyTemplate {
fn greet(name: &str) -> String {
format!("Hello {}", name)
}
}
If you want to call a closure which is a field, you’ll need to follow Rust’s syntax by surrounding the call with parens:
#[derive(Template)]
#[template(source = "{{ (closure)(12) }}", ext = "txt")]
struct MyTemplate {
closure: fn(i32) -> i32,
}
Calling functions
If you only provide a function name, askama will assume it’s a method. If you want to call a function, you will need to use a path instead:
{# This is the equivalent of `self.method()`. #}
{{ method() }}
{# This is the equivalent of `self::function()`, which will call the
`function` function from the current module. #}
{{ self::function() }}
{# This is the equivalent of `super::b::f()`. #}
{{ super::b::f() }}
Creating structs
Askama supports creating structs similarly as in Rust:
{{ MyStruct { field1: 1, field2: "foo" }.to_string() }}
Using base structs is supported too:
{{ MyStruct { field1: 1, ..other_struct } }}
{{ MyStruct { field1: 1, ..Default::default() } }}
Template inheritance
Template inheritance allows you to build a base template with common elements that can be shared by all inheriting templates. A base template defines blocks that child templates can override.
Base template
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{{ title }} - My Site{% endblock %}</title>
{% block head %}{% endblock %}
</head>
<body>
<div id="content">
{% block content %}<p>Placeholder content</p>{% endblock %}
</div>
</body>
</html>
The block tags define three blocks that can be filled in by child
templates. The base template defines a default version of the block.
A base template must define one or more blocks in order to enable
inheritance. Blocks can only be specified at the top level of a template
or inside other blocks, not inside if/else branches or in for-loop
bodies.
It is also possible to use the name of the block in endblock (both in
declaration and use):
{% block content %}<p>Placeholder content</p>{% endblock content %}
Child template
Here’s an example child template:
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
<style>
</style>
{% endblock %}
{% block content %}
<h1>Index</h1>
<p>Hello, world!</p>
{{ super() }}
{% endblock %}
The extends tag tells the code generator that this template inherits
from another template. It will search for the base template relative to
itself before looking relative to the template base directory. It will
render the top-level content from the base template, and substitute
blocks from the base template with those from the child template. Inside
a block in a child template, the super() macro can be called to render
the parent block’s contents.
Because top-level content from the child template is thus ignored, the extends
tag doesn’t support whitespace control:
{%- extends "base.html" +%}
The above code is rejected because we used - and +. For more information
about whitespace control, take a look here.
Block fragments
Additionally, a block can be rendered by itself. This can be useful when
you need to decompose your template for partial rendering, without
needing to extract the partial into a separate template or macro. This
can be done with the block parameter.
#[derive(Template)]
#[template(path = "...", block = "my_block")]
struct BlockFragment {
name: String,
}
HTML escaping
Askama by default escapes variables if it thinks it is rendering HTML
content. It infers the escaping context from the extension of template
filenames, escaping by default if the extension is one of html, htm,
or xml. When specifying a template as source in an attribute, the
ext attribute parameter must be used to specify a type. Additionally,
you can specify an escape mode explicitly for your template by setting
the escape attribute parameter value (to none or html).
Askama escapes <, >, &, ", and ', according to the
OWASP escaping recommendations. Use the safe filter to
prevent escaping for a single expression, or the escape (or e)
filter to escape a single expression in an unescaped context.
#[derive(Template)]
#[template(source = "{{strvar}}")]
struct TestTemplate {
strvar: String,
}
fn main() {
let s = TestTemplate {
strvar: "// my <html> is \"unsafe\" & should be 'escaped'".to_string(),
};
assert_eq!(
s.render().unwrap(),
"// my <html> is "unsafe" & \
should be 'escaped'"
);
}
Control structures
For
Loop over each item in an iterator. For example:
<h1>Users</h1>
<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
You can filter items by adding an if condition:
<h1>Users</h1>
<ul>
{% for user in users if user.is_activated %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
You can add an optional {% else %} block that is entered if the loop was never
entered, either because the iterator was empty, or the filter condition was never
match.
<h1>Users</h1>
<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% else %}
<li>No users</li>
{% endfor %}
</ul>
Inside for-loop blocks, some useful variables are accessible:
- loop.index: current loop iteration (starting from 1)
- loop.index0: current loop iteration (starting from 0)
- loop.first: whether this is the first iteration of the loop
- loop.last: whether this is the last iteration of the loop
<h1>Users</h1>
<ul>
{% for user in users %}
{% if loop.first %}
<li>First: {{user.name}}</li>
{% else %}
<li>User#{{loop.index}}: {{user.name}}</li>
{% endif %}
{% endfor %}
</ul>
If
The if statement essentially mirrors Rust’s if expression,
and is used as you might expect:
{% if users.len() == 0 %}
No users
{% else if users.len() == 1 %}
1 user
{% elif users.len() == 2 %}
2 users
{% else %}
{{ users.len() }} users
{% endif %}
If Let
Additionally, if let statements are also supported and similarly
mirror Rust’s if let expressions:
{% if let Some(user) = user %}
{{ user.name }}
{% else %}
No user
{% endif %}
is (not) defined
You can use is (not) defined to ensure a variable exists (or not):
{% if x is defined %}
x is defined!
{% endif %}
{% if y is not defined %}
y is not defined
{% else %}
y is defined
{% endif %}
You can combine conditions with this feature and even use it in expressions:
{% if x is defined && x == "12" && y == Some(true) %}
...
{% endif %}
<script>
// It will generate `const x = true;` (or false is `x` is not defined).
const x = {{ x is defined }};
</script>
Due to proc-macro limitations, askama can only see the fields of your current type and the variables declared in the templates. Because of this, you can not check if a field or a function is defined:
{% if x.y is defined %}
This code will not compile
{% endif %}
Match
In order to deal with Rust enums in a type-safe way, templates support
match blocks from version 0.6. Here is a simple example showing how to
expand an Option:
{% match item %}
{% when Some with ("foo") %}
Found literal foo
{% when Some with (val) %}
Found {{ val }}
{% when None %}
{% endmatch %}
That is, a {% match %} block may contain whitespaces (but no other literal content)
and comment blocks, followed by a number of {% when %} blocks
and an optional {% else %} block.
Like in Rust, the matching is done against a pattern. Such a pattern may be a literal, e.g.
{% match multiple_choice_answer %}
{% when 3 %} Correct!
{% else %} Sorry, the right answer is "3".
{% endmatch %}
Or some more complex type, such as a Result<T, E>:
{% match result %}
{% when Ok(val) %} Good: {{ val }}.
{% when Err(err) %} Bad: {{ err }}.
{% endmatch %}
Using the placeholder _ to match against any value without capturing the datum, works too.
The wildcard operator .. is used to match against an arbitrary amount of items,
and the same restrictions as in Rust, e.g. that it can be used only once in a slice or struct:
{% match list_of_ints %}
{% when [first, ..] %} The list starts with a {{ first }}
{% when _ %} The list is empty.
{% endmatch %}
The {% else %} node is syntactical sugar for {% when _ %}.
If used, it must come last, after all other {% when %} blocks:
{% match answer %}
{% when Ok(42) %} The answer is "42".
{% else %} No answer wrong answer?
{% endmatch %}
A {% match %} must be exhaustive, i.e. all possible inputs must have a case.
This is most easily done by providing an {% else %} case,
if not all possible values need an individual handling.
Because a {% match %} block could not generate valid code otherwise,
you have to provide at least one {% when %} case and/or an {% else %} case.
You can also match against multiple alternative patterns at once:
{% match number %}
{% when 1 | 4 | 86 %} Some numbers
{% when n %} Number is {{ n }}
{% endmatch %}
For better interoperability with linters and auto-formatters like djLint,
you can also use an optional {% endwhen %} node to close a {% when %} case:
{% match number %}
{% when 0 | 2 | 4 | 6 | 8 %}
even
{% endwhen %}
{% when 1 | 3 | 5 | 7 | 9 %}
odd
{% endwhen %}
{% else %}
unknown
{% endmatch %}
Referencing and dereferencing variables
If you need to put something behind a reference or to dereference it, you
can use & and * operators:
{% let x = &"bla" %}
{% if *x == "bla" %}
Just talking
{% else if x == &"another" %}
Another?!
{% endif %}
They have the same effect as in Rust and you can put multiple of them:
{% let x = &&"bla" %}
{% if *&**x == "bla" %}
You got it
{% endif %}
Question mark operator
You can use the ? operator similarly as ? operator in Rust but only on Result types.
{{ some_result? }}
{% let value = some_result? %}
When the operator unwraps erroneous value, the template rendering will fail with
askama::Error::Custom error that
wraps the error.
Note that this operator currently only works with Result types - it doesn’t support Option types.
Include
The include statement lets you split large or repetitive blocks into separate template files. Included templates get full access to the context in which they’re used, including local variables like those from loops:
{% for i in iter %}
{% include "item.html" %}
{% endfor %}
item.html file:
* Item: {{ i }}
The path to include must be a string literal, so that it is known at
compile time. Askama will try to find the specified template relative
to the including template’s path before falling back to the absolute
template path. Use include within the branches of an if/else
block to use includes more dynamically.
Expressions
Askama supports string literals ("foo") and integer literals (1).
It supports almost all binary operators that Rust supports,
including arithmetic, comparison and logic operators.
The parser applies the same operator precedence as the Rust compiler.
Expressions can be grouped using parentheses.
{{ 3 * 4 / 2 }}
{{ 26 / 2 % 7 }}
{{ 3 % 2 * 6 }}
{{ 1 * 2 + 4 }}
{{ 11 - 15 / 3 }}
{{ (4 + 5) % 3 }}
The HTML special characters &, < and > will be replaced with their
character entities unless the escape mode is disabled for a template,
or the filter | safe is used.
Methods can be called on variables that are in scope, including self.
Warning: if the result of an expression (a {{ }} block) is
equivalent to self, this can result in a stack overflow from infinite
recursion. This is because the Display implementation for that expression
will in turn evaluate the expression and yield self again.
Expressions containing bit-operators
In Askama, the binary AND, OR, and XOR operators (called &, |, ^ in Rust, resp.),
are renamed to bitand, bitor, xor to avoid confusion with filter expressions.
They still have the same operator precedence as in Rust.
E.g. to test if the least significant bit is set in an integer field:
{% if my_bitset bitand 1 != 0 %}
It is set!
{% endif %}
Type conversion
You can use the as operator in {{ … }}
expressions, and {% … %} blocks. It works the same as in Rust, but with some deliberate
restrictions:
- You can only use primitive types
like
i32orf64both as source variable type and as target type. - If the source is a reference to a primitive type, e.g.
&&&bool, then askama automatically dereferences the value until it gets the underlyingbool.
String concatenation
As a short-hand for {{ a }}{{ b }}{{ c }} you can use the concat operator ~: {{ a ~ b ~ c }}.
The tilde ~ has to be surrounded by spaces to avoid confusion with the whitespace control operator.
Templates in templates
Using expressions, it is possible to delegate rendering part of a template to another template. This makes it possible to inject modular template sections into other templates and facilitates testing and reuse.
use askama::Template;
#[derive(Template)]
#[template(source = "Section 1: {{ s1 }}", ext = "txt")]
struct RenderInPlace<'a> {
s1: SectionOne<'a>
}
#[derive(Template)]
#[template(source = "A={{ a }}\nB={{ b }}", ext = "txt")]
struct SectionOne<'a> {
a: &'a str,
b: &'a str,
}
let t = RenderInPlace { s1: SectionOne { a: "a", b: "b" } };
assert_eq!(t.render().unwrap(), "Section 1: A=a\nB=b")
Note that if your inner template like SectionOne renders HTML content, then you may want to
disable escaping when injecting it into an outer template, e.g. {{ s1 | safe }}.
Otherwise it will render the HTML content literally, because
askama escapes HTML variables by default.
Instead of disabling escaping for this template type at every single invocation within your template, you can alternatively mark the template itself as safe:
impl askama::filters::HtmlSafe for SectionOne<'_> {}
See the example render in place, which demonstrates using a vector of templates in a for block.
Comments
Askama supports block comments delimited by {# and #}.
{# A Comment #}
Like Rust, Askama also supports nested block comments.
{#
A Comment
{# A nested comment #}
#}
Recursive Structures
Recursive implementations should preferably use a custom iterator and
use a plain loop. If that is not doable, call .render()
directly by using an expression as shown below.
use askama::Template;
#[derive(Template)]
#[template(source = r#"
{{ name }} {
{% for item in children %}
{{ item.render()? }}
{% endfor %}
}
"#, ext = "html", escape = "none")]
struct Item<'a> {
name: &'a str,
children: &'a [Item<'a>],
}
Macros
Macros are a jinja mechanism to declare reusable snippets. A macro can declare a set of required and optional arguments. Additionally, macros inherit the variable scope from their callsite. Defining and invoking a simple macro looks like this:
{% macro heading(required_arg, optional_arg = "default subtitle") %}
<h1>{{required_arg}}</h1>
<h2>{{optional_arg}}</h2>
{{ variable_in_scope }}
{% endmacro %}
{# Variable scope that will be passed into macro invocations #}
{% set variable_in_scope = 5 %}
{# Invoke the macro by supplying all arguments #}
{{ heading("test", "good subtitle") }}
{# Invoke the macro by leaving out the optional argument `optional_arg` #}
{# This will use the default value `default subtitle` #}
{{ heading("test") }}
You can add type annotation to macro arguments (works with default values as well):
{%- macro test(value: Option<u32>, extra: Option<u32> = None) -%}
{% if let Some(value) = value -%}value is {{value}}{% endif -%}
{% if let Some(extra) = title -%}extra is {{extra}}{% endif -%}
{% endmacro -%}
Optionally, {% endmacro %} statements can also contain the macro’s name, which would look something like this for the above example:
{% macro heading(required_arg, optional_arg = "default subtitle") %}
{# ... #}
{% endmacro heading %}
Imports & Scopes
To have a small library of reusable snippets, it’s best to declare the macros in some external file. This file can then be imported with a named scope into your template. Moving the macro declaration above into the file macro.html, importing and then invoking it would look like this:
{% import "macro.html" as scope %}
{{ scope::heading("test") }}
Named Arguments
Additionally to specifying arguments positionally, you can also pass arguments by name. This allows passing the arguments in any order:
{% macro heading(title, font_weight = "normal", font_size = 13) %}
<h1 style="font-weight: {{ font_weight }}; font-size: {{ font_size }};">
{{ title }}
</h1>
{% endmacro %}
{# using positional arguments #}
{{ heading("Super Heading", "bold", 13) }}
{# using named arguments #}
{{ heading(title = "Super Heading", font_weight = "bold") }}
{{ heading(title = "Super Heading", font_weight = "bold", font_size = 23) }}
{{ heading(title = "Super Heading", font_size = 42, font_weight = "bold") }}
Both ways of invoking a macro can even be mixed, though optional arguments always have to come last (after all arguments specified positionally):
{{ heading("Super Heading", font_weight = "bold", font_size = 26) }}
{{ heading("Super Heading", font_size = 26, font_weight = "bold") }}
{{ heading("Super Heading", "bold", font_size = 26) }}
Another thing to note, if a named argument is referring to an argument that would be used for a non-named argument, it will error:
{% macro heading(arg1, arg2, arg3, arg4) %}
{% endmacro %}
{{ heading("something", "b", arg4 = "ah", arg2 = "title") }}
In here it’s invalid because arg2 is the second argument and would be used by
"b". So either you replace "b" with arg3="b" or you pass "title" before:
{{ heading("something", arg3 = "b", arg4 = "ah", arg2 = "title") }}
{# Equivalent of: #}
{{ heading("something", "title", "b", arg4 = "ah") }}
Macro Call Blocks
There is a second way to invoke macros, using the call block syntax. This syntax allows your invocation to have a “body”. Within the macro, a special variable called caller will be defined, that behaves like a function and can insert the given body at any place:
{% macro centered() %}
<center>
{# insert the invocation's body here: #}
{{ caller() }}
<center>
{% endmacro %}
{# This macro has to use the call block syntax, because it's expecting a body: #}
{% call centered() %}
This text will be centered
{% endcall %}
Invoking this macro using the call expression syntax shown above ({{ centered() }}) will fail, because the macro is expecting the variable caller() to exist - but only call-block invocations define it.
However, you can declare macros in a way that allows invoking them with and without body:
{% macro render_dialog(title, class="dialog") -%}
<div class="{{ class }}">
<h2>{{ title }}</h2>
<div class="contents">
{% if caller is defined %}
{{ caller() }}
{% else %}
Empty dialog without content
{% endif %}
</div>
</div>
{%- endmacro %}
{# invoking it without body: no `caller` will be defined #}
{{ render_dialog("Empty Dialog") }}
{# invoking it with body: #}
{% call render_dialog("Nice Dialog") %}
This is a simple dialog rendered by using a macro and
a call block.
{% endcall %}
You can also use caller in variable declarations:
{%- macro test() -%}
{%- set content = caller() -%}
-> `{{content}}` <-
{%~ endmacro -%}
{% call test() %}bla{% endcall -%}
In this case it will display:
-> `bla` <-
Macro Call Block Arguments
There is a reason why caller is a function instead of a variable.
It allows passing arguments, as well as calling it multiple times from the macro!
Here is an example macro that invokes the caller() method with the argument user.
To invoke this macro, your call-block has to declare arguments itself:
{% macro dump_users(users) -%}
<ul>
{%- for user in users %}
<li><p>{{ user.username }}</p>{{ caller(user) }}</li>
{%- endfor %}
</ul>
{%- endmacro %}
{# This callblock declares the argument `user` for `caller`: #}
{% call(user) dump_users(list_of_users) %}
<dl>
<dt>Realname</dt>
<dd>{{ user.realname }}</dd>
<dt>Description</dt>
<dd>{{ user.description }}</dd>
</dl>
{% endcall %}
Nesting Macros With Content
At certain levels of abstraction, it might make sense to declare a macro that has a body - but will pass the body into another macro invocation.
Macro invocations instantly overwrite the caller variable with their own. To be able to access the outer caller variable, a small trick is required:
{% macro container() %}
<div class="container">
{{ caller() }}
</div>
{% endmacro %}
{% macro outer_container() %}
{# Create an alias to our `caller`, so we can access it within container: #}
{% set outer_caller = caller %}
<div class="outer-container">
{# nested macro invocation - will overwrite the `caller` variable: #}
{% call container() %}
{{ outer_caller() }}
{% endcall %}
</div>
{% endmacro %}
Calling Rust macros
It is possible to call rust macros directly in your templates:
{% let s = format!("{}", 12) %}
One important thing to note is that contrary to the rest of the expressions, Askama cannot know if a token given to a macro is a variable or something else, so it will always default to generate it “as is”. So if you have:
macro_rules! test_macro{
($entity:expr) => {
println!("{:?}", &$entity);
}
}
#[derive(Template)]
#[template(source = "{{ test_macro!(entity) }}", ext = "txt")]
struct TestTemplate<'a> {
entity: &'a str,
}
It will not compile, telling you it doesn’t know entity. It didn’t infer
that entity was a field of the current type unlike usual. You can go
around this limitation by binding your field’s value into a variable:
{% let entity = entity %}
{{ test_macro!(entity) }}
Opt-in features
Some features in askama are opt-in to reduce the amount of dependencies, and to keep the compilation time low.
To opt-in to a feature, you can use features = […].
E.g. if you want to use the filter |json,
you have to opt-in to the feature "serde_json":
[dependencies]
askama = { version = "0.14.0", features = ["serde_json"] }
Please read the Cargo manual for more information.
Default features
Any semver-compatible upgrade
(e.g. askama = "0.14.1" to askama = "0.14.2") will keep the same list of default features.
We will treat upgrades to a newer dependency version as a semver breaking change.
"default"
You can opt-out of using the feature flags by using
default-features = false:
[dependencies]
askama = { version = "0.14.0", default-features = false }
Without default-features = false, i.e with default features enabled,
the following features are automatically selected for you:
default = ["config", "derive", "std", "urlencode"]
This should encompass most features an average user of askama might need.
If you are writing a library that depends on askama, and if you want it to be usable in by other users and in other projects, then you should probably opt-out of features you do not need.
"derive"
enabled by "default"
This feature enables #[derive(Template)]. Without it the trait askama::Template will still be
available, but if you want to derive a template, you have to manually depend on askama_macros.
askama_macros should be used with the same features as askama.
Not using this feature might be useful e.g. if you are writing a library with manual filters
for askama, without any templates. It might also very slightly speed-up the compilation,
because more dependencies can be compiled in parallel, because askama won’t transitively depend
on e.g. syn or proc-macro2. On the author’s PC the compilation of a trivial hello-world example
was about 0.2s faster without the feature when compiled in release mode.
If you are writing a library that uses askama, consider not using this default-feature.
"config"
enabled by "default"
Enables compile time configurations.
"urlencode"
enabled by "default"
Enables the filters |urlencode and |urlencode_strict.
Addition features
Please note that we reserve the right to add more features to the current list, without labeling it as a semver breaking change. The newly added features might even depend on a newer rustc version than the previous list.
The most useful catch-all feature for a quick start might be "full",
which enables all implemented features, i.e.:
full = ["default", "code-in-doc", "serde_json"]
In production or once your project is “maturing” you might want to manually opt-in to any needed
features with a finer granularity instead of depending on "full".
"serde_json"
enabled by "full"
This feature depends on the crate serde_json.
We won’t treat upgrades to a newer serde_json version as a semver breaking change,
even if it raises the MSRV.
Enables the filter |json.
"code-in-doc"
enabled by "full"
This feature depends on the crate pulldown-cmark.
We won’t treat upgrades to a newer pulldown-cmark version as a semver breaking change,
even if it raises the MSRV.
Enables using documentations as template code.
“Anti-features” in a #![no_std] environment
Opting-out of the default features "std" and "alloc" is only interesting for the use
in a #![no_std] environment.
Please find more information in The Embedded Rust Book.
"alloc"
enabled by "default"
Without the default feature "alloc" askama can be used in a #![no_std] environment.
The method Template::render() will be absent, because askama won’t have access to a default allocator.
Many filters need intermediate allocations, and won’t be usable without this feature.
You can still render templates using e.g.
no_std_io2::io::Cursor or
embedded_io::Write
"std"
enabled by "default"
Without the feature "std" askama can be used in a #![no_std] environment.
The method Template::write_into() will be absent, because askama won’t have access to standard IO operations.
Enabling "std" enables "alloc", too.
Filters
Values such as those obtained from variables can be post-processed
using filters.
Filters are applied to values using the pipe symbol (|) and may
have optional extra arguments in parentheses.
Filters can be chained, in which case the output from one filter
is passed to the next.
{{ "HELLO" | lower }}
Askama has a collection of built-in filters, documented below, but can also include custom filters.
Additionally, the json filter is included in the built-in filters, but is disabled by default.
Enable it with Cargo features (see below for more information).
Built-In Filters
Built-in filters that take (optional) arguments can be called with named arguments, too. The order of the named arguments does not matter, but named arguments must come after positional (i.e. unnamed) arguments.
E.g. the filter pluralize takes two optional arguments: singular and plural
which are singular = "" and plural = "s" by default.
If you are fine with the default empty string for the singular, and you only want to set a
specific plural, then you can call the filter like dog{{ count | pluralize(plural = "gies") }}.
assigned_or
{{ variable_or_expression | assigned_or(fallback) }}
If the variable on the left-hand side is in its “default” state, e.g. an empty "" string,
a 0 integer, a None optional, or an Err(_) result, then the fallback value is printed.
Otherwise the value.
{% let greeting = Some("Hello") %}
{{ greeting.as_ref() | assigned_or("Hi") }}
Hello
If the value is an identifier, then it is first tested of the variable name is defined.
See also [|defined_or][#defined_or].
capitalize
enabled by"alloc"
enabled by"default"
{{ text_to_capitalize | capitalize }}
Capitalize a value. The first character will be uppercase, all others lowercase:
{{ "hello" | capitalize }}
Output:
Hello
center
enabled by"alloc"
enabled by"default"
{{ text_to_center | center(length) }}
Centers the value in a field of a given width:
-{{ "a" | center(5) }}-
Output:
- a -
default
{{ variable_or_expression | default(default_value) }}
{{ variable_or_expression | default(default_value, [[boolean =] true]) }}
This filter works like the Jinja filter of the same name.
If the second argument is not a boolean true, then the filter behaves like [|defined_or][#defined_or].
If it is supplied and true, then the filter behaves like [|assigned_or][#assigned_or].
This filter exists for compatibility with Jinja.
Askama provides [|defined_or][#defined_or] and [|assigned_or][#assigned_or] which both
better express the intention and should generally be used instead of this filter.
defined_or
{{ variable | defined_or(fallback) }}
The left-hand side of the filter must be an identifier.
Return a fallback value if the identifier is undefined:
{% let greeting = "Hello" %}
{{ greeting | defined_or("Hi") }}
Since the variable greeting is defined, the output is its value: Hello.
If you remove the variable, then the output is the default value: Hi:
{{ greeting | defined_or("Hi") }}
See also [|assigned_or][#assigned_or].
deref
{{ expression | deref }}
Dereferences the given argument.
{% let s = String::from("a") | ref %}
{% if s | deref == String::from("b") %}
{% endif %}
will become:
let s = &String::from("a");
if *s == String::from("b") {}
escape | e
{{ text_to_escape | e }}
{{ text_to_escape | escape }}
{{ text_to_escape | escape(escaper) }}
Escapes HTML characters in strings:
{{ "Escape <>&" | e }}
Output:
Escape <>&
Optionally, it is possible to specify and override which escaper is used.
Consider a template where the escaper is configured as escape = "none".
However, somewhere escaping using the HTML escaper is desired.
Then it is possible to override and use the HTML escaper like this:
{{ "Don't Escape <>&" | escape }}
{{ "Don't Escape <>&" | e }}
{{ "Escape <>&" | escape("html") }}
{{ "Escape <>&" | e("html") }}
Output:
Don't Escape <>&
Don't Escape <>&
Escape <>&
Escape <>&
filesizeformat
{{ number_of_bytes | filesizeformat }}
Returns adequate string representation (in KB, ..) of number of bytes:
{{ 1024 | filesizeformat }}
Output:
1.02 KB
Control the resulting precision with the optional precision argument:
{{ 1024 | filesizeformat(precision = 3) }}
Output:
1.024 KB
fmt
enabled by"alloc"
enabled by"default"
{{ expression | fmt("format_string") }}
Formats arguments according to the specified format
The second argument to this filter must be a string literal (as in normal
Rust). The two arguments are passed through to format!() by
the Askama code generator, but the order is swapped to support filter
composition.
{{ value | fmt("{:?}") }}
As an example, this allows filters to be composed like the following.
Which is not possible using the format filter.
{{ value | capitalize | fmt("{:?}") }}
format
enabled by"alloc"
enabled by"default"
{{ "format_string" | format([variables ...]) }}
Formats arguments according to the specified format.
The first argument to this filter must be a string literal (as in normal Rust).
All arguments are passed through to format!() by the Askama code generator.
{{ "{:?}" | format(var) }}
indent
{{ text_to_indent | indent(width, [first], [blank]) }}
Indent newlines with width spaces.
{{ "hello\nfoo\nbar" | indent(4) }}
Output:
hello
foo
bar
The first argument can also be a string that will be used to indent lines.
The first line and blank lines are not indented by default.
The filter has two optional [bool] arguments first and blank, that can be set to true
to indent the first and blank lines, resp.:
{{ "hello\n\nbar" | indent("$ ", true, true) }}
Output:
$ hello
$
$ bar
join
{{ iterable | join(separator) }}
Joins iterable into a string separated by provided argument.
array = &["foo", "bar", "bazz"]
{{ array | join(", ") }}
Output:
foo, bar, bazz
linebreaks
{{ text_to_break | linebreaks }}
Replaces line breaks in plain text with appropriate HTML.
A single newline becomes an HTML line break <br> and a new line followed by a blank line becomes a paragraph break <p>.
{{ "hello\nworld\n\nfrom\naskama" | linebreaks }}
Output:
<p>hello<br />world</p><p>from<br />askama</p>
linebreaksbr
{{ text_to_break | linebreaksbr }}
Converts all newlines in a piece of plain text to HTML line breaks.
{{ "hello\nworld\n\nfrom\naskama" | linebreaks }}
Output:
hello<br />world<br /><br />from<br />askama
paragraphbreaks
{{ text_to_break | paragraphbreaks }}
A new line followed by a blank line becomes <p>, but, unlike linebreaks, single new lines are ignored and no <br/> tags are generated.
Consecutive double line breaks will be reduced down to a single paragraph break.
This is useful in contexts where changing single line breaks to line break tags would interfere with other HTML elements, such as lists and nested <div> tags.
{{ "hello\nworld\n\nfrom\n\n\n\naskama" | paragraphbreaks }}
Output:
<p>hello\nworld</p><p>from</p><p>askama</p>
lower | lowercase
enabled by"alloc"
enabled by"default"
{{ text_to_convert | lower }}
{{ text_to_convert | lowercase }}
Converts to lowercase.
{{ "HELLO" | lower }}
Output:
hello
pluralize
{{ integer | pluralize }}
{{ integer | pluralize([singular = ""], [plural = "s"]) }}
Select a singular or plural version of a word, depending on the input value.
If the value of self.count is +1 or -1, then “cat” is returned, otherwise “cats”:
cat{{ count | pluralize }}
You can override the default empty singular suffix, e.g. to spell “doggo” for a single dog:
dog{{ count | pluralize("go") }}
If the word cannot be declined by simply adding a suffix, then you can also override singular and the plural, too:
{{ count | pluralize("mouse", "mice") }}
More complex languages that know multiple plurals might be impossible to implement with this filter, though.
ref
{{ expression | ref }}
Creates a reference to the given argument.
{{ "a" | ref }}
{{ self.x | ref }}
will become:
&"a"
&self.x
reject
This filter filters out values matching the given value/filter.
With this data:
vec![1, 2, 3, 1]
And this template:
{% for elem in data|reject(1) %}{{ elem }},{% endfor %}
Output will be:
2,3,
For more control over the filtering, you can use a callback instead. Declare a function:
fn is_odd(value: &&u32) -> bool {
**value % 2 != 0
}
Then you can pass the path to the is_odd function:
{% for elem in data|reject(crate::is_odd) %}{{ elem }},{% endfor %}
Output will be:
2,
safe
{{ expression | safe }}
Marks a string (or other Display type) as safe. By default all strings are escaped according to the format.
{{ "<p>I'm Safe</p>" | safe }}
Output:
<p>I'm Safe</p>
title | titlecase
enabled by"alloc"
enabled by"default"
{{ text_to_convert | title }}
{{ text_to_convert | titlecase }}
Return a title cased version of the value. Words will start with uppercase letters, all remaining characters are lowercase.
{{ "hello WORLD" | title }}
Output:
Hello World
trim
enabled by"alloc"
enabled by"default"
{{ text_to_trim | trim }}
Strip leading and trailing whitespace.
{{ " hello " | trim }}
Output:
hello
truncate
{{ text_to_truncate | truncate(length) }}
Limit string length, appends ‘…’ if truncated.
{{ "hello" | truncate(2) }}
Output:
he...
unique
Returns an iterator with all duplicates removed.
This filter is only available with the std feature enabled.
With this data:
vec!["a", "b", "a", "c"]
And this template:
{% for elem in data|unique %}{{ elem }},{% endfor %}
Output will be:
a,b,c,
upper | uppercase
enabled by"alloc"
enabled by"default"
{{ text_to_convert | upper }}
{{ text_to_convert | uppercase }}
Converts to uppercase.
{{ "hello" | upper }}
Output:
HELLO
urlencode | urlencode_strict
enabled by"urlencode"
enabled by"default"
{{ text_to_escape | urlencode }}
{{ text_to_escape | urlencode_strict }}
Percent encodes the string. Replaces reserved characters with the % escape character followed by a byte value as two hexadecimal digits.
{{ "hello?world" | urlencode }}
Output:
hello%3Fworld
With |urlencode all characters except ASCII letters, digits, and _.-~/ are escaped.
With |urlencode_strict a forward slash / is escaped, too.
wordcount
{{ text_with_words | wordcount }}
Count the words in that string.
{{ "askama is sort of cool" | wordcount }}
Output:
5
Optional / feature gated filters
The following filters can be enabled by requesting the respective feature in the Cargo.toml dependencies section, e.g.
[dependencies]
askama = { version = "0.12", features = ["serde_json"] }
json | tojson
enabled by "serde_json"
{{ value_to_serialize | json }}
{{ value_to_serialize | json(indent) }}
Enabling the serde_json feature will enable the use of the json filter.
This will output formatted JSON for any value that implements the required
Serialize trait.
The generated string does not contain ampersands &, chevrons < >, or apostrophes '.
To use it in a <script> you can combine it with the safe filter.
In HTML attributes, you can either use it in quotation marks "{{data | json}}" as is,
or in apostrophes with the (optional) safe filter '{{data | json | safe}}'.
In HTML texts the output of e.g. <pre>{{data | json | safe}}</pre> is safe, too.
Good: <li data-extra="{{data | json}}">…</li>
Good: <li data-extra='{{data | json | safe}}'>…</li>
Good: <pre>{{data | json | safe}}</pre>
Good: <script>var data = {{data | json | safe}};</script>
Bad: <li data-extra="{{data | json | safe}}">…</li>
Bad: <script>var data = {{data | json}};</script>
Bad: <script>var data = "{{data | json | safe}}";</script>
Ugly: <script>var data = "{{data | json}}";</script>
Ugly: <script>var data = '{{data | json | safe}}';</script>
By default, a compact representation of the data is generated, i.e. no whitespaces are generated between individual values. To generate a readable representation, you can either pass an integer how many spaces to use as indentation, or you can pass a string that gets used as prefix:
Prefix with four spaces:
<textarea>{{data | tojson(4)}}</textarea>
Prefix with two characters:
<p>{{data | tojson("\u{a0}\u{a0}")}}</p>
Custom Filters
To define your own filters, either have a module named filters in scope of the context of your
#[derive(Template]) struct, and define the filters as functions within this module;
or call the filter with a path, e.g. {{ value | some_module::my_filter }}. Alternatively, you can also place your custom filter functions in a crate called filters added as dependency to your askama project.
The expressions {{ value | my_filter }} and {{ value | filters::my_filter }} behave identically,
unless “my_filter” happens to be a built-in filter.
Note that built-in filters take precedence, so your custom filters will always be shadowed by built-in filters (if they have the same name). To avoid this, call your custom filters with a full path.
Anatomy of a custom filter function
#[askama::filter_fn]
pub fn example_filter1(
// Value that's piped into the filter within the jinja template.
// This can be of any type. `impl Display` is just an example.
value: impl Display,
// This is askama's runtime values environment. Together with
// values, these two arguments are always passed into a custom filter.
env: &dyn askama::Values
) -> askama::Result<String> {
Ok(format!("{value} | example_filter1"))
}
The basic anatomy of a filter function must always look like this:
- The first argument is the value your custom filter function is applied to during a filter invocation. In this template expression:
{{ 1337 | example_filter1 }}, the value1337will be passed in as first argument to your filter function. - The second argument is always of type
values: &dyn askama::Values, storing askama’s runtime values environment. - Custom filter functions’ return type must be
askama::Result<T>, whereTof the last filter invocation of a filter chain mustimpl Display. In this exemplary filter chain:{{ 1337 | multiply | final_filter }}, themultiplyfilter may returnaskama::Result<MyCustomNonDisplayableStruct>, butfinal_filtermust returnaskama::Result<T>withT: Display, otherwise your template will fail to compile.
Additionally to this basic structure, your custom filter function can also have:
An arbitrary amount of required arguments:
#[askama::filter_fn]
pub fn example_filter2<T: ToString>(
value: impl Display, env: &dyn askama::Values,
// Custom arguments that need to be specified when calling your filter
required0: impl Display,
required1: T,
required2: usize
) -> askama::Result<String> { /* ... */ }
An arbitrary amount of optional arguments (must be located after required arguments in your function signature):
#[askama::filter_fn]
pub fn example_filter3(
value: impl Display, // filter input
env: &dyn askama::Values, // askama runtime values environment
required0: impl Display,
// Custom arguments that may optionally be specified when calling your filter
#[optional(None)] optional0: Option<&str>,
#[optional(Some("I am the default value"))] optional1: Option<&str>,
#[optional("I am the default value")] optional2: &str,
) -> askama::Result<String> { /* ... */ }
Calling custom filters
Thanks to the askama::filter_fn macro, invocations to your custom filter functions can also use named arguments - though currently providing diagnostic compile error messages that are a lot less readable compared to builtin filters, when you’re using them wrong in your templates. All of these are valid invocations of the filter functions above:
{{ 1337 | example_filter2("value0", "value1", 2) }}
{{ "1337" | example_filter2(required0 = "req0", required1 = "req1", required2 = 2) }}
{{ 1337 | example_filter3("req0") }}
{{ 1337 | example_filter3("req0", None) }}
{{ "1337" | example_filter3("req0", None, None) }}
{{ "1337" | example_filter3("req0", None, Some("opt1"), "opt2") }}
{{ "1337" | example_filter3("req0", optional2 = "opt2") }}
{{ "1337" | example_filter3(required0 = "req0", optional2 = "opt2") }}
Reference Value Passing Issues
Due to the nature of askama’s generated code, you will often encounter a mix of by-value and various degrees of references to your variables in the jinja template. If you declare your custom filter input value as one concrete type, like &str, you will often be confronted with the problem of having to (de)-reference your input variables: {{ value | filter }}, {{ *value | filter }}, {{ **value | filter }}, …
To avoid this, try to declare your filter’s input argument using trait bounds, which are also implemented for references. For example, instead of:
#[askama::filter_fn]
pub fn example_filter4(value: &str, env: &dyn askama::Values) -> askama::Result<String> {}
instead specify value with a trait bound of Display:
#[askama::filter_fn]
pub fn example_filter4(value: impl Display, env: &dyn askama::Values) -> askama::Result<String> {}
as Display is implemented for &str as well as for &&str, &&&str, ….
This cleans up your invocation sites, as no dereferencing (and no additional compile roundtripping) is required.
Examples
Implementing a filter that replaces all instances of "oo" for "aa".
use askama::Template;
#[derive(Template)]
#[template(source = "{{ s | myfilter }}", ext = "txt")]
struct MyFilterTemplate<'a> {
s: &'a str,
}
// Any filter defined in the module `filters` is accessible in your template.
mod filters {
// This filter does not have extra arguments
#[askama::filter_fn]
pub fn myfilter<T: std::fmt::Display>(
value: T,
_env: &dyn askama::Values,
) -> askama::Result<String> {
let s = s.to_string();
Ok(s.replace("oo", "aa"))
}
}
fn main() {
let t = MyFilterTemplate { s: "foo" };
assert_eq!(t.render().unwrap(), "faa");
}
Implementing a filter that replaces all instances of "oo" for n times "a".
use askama::Template;
#[derive(Template)]
#[template(source = "{{ s | myfilter(4) }}", ext = "txt")]
struct MyFilterTemplate<'a> {
s: &'a str,
}
// Any filter defined in the module `filters` is accessible in your template.
mod filters {
// This filter requires a `usize` input when called in templates
#[askama::filter_fn]
pub fn myfilter<T: std::fmt::Display>(
s: T,
_env: &dyn askama::Values,
n: usize,
) -> askama::Result<String> {
let s = s.to_string();
let mut replace = String::with_capacity(n);
replace.extend((0..n).map(|_| "a"));
Ok(s.replace("oo", &replace))
}
}
fn main() {
let t = MyFilterTemplate { s: "foo" };
assert_eq!(t.render().unwrap(), "faaaa");
}
Runtime values
It is possible to access runtime values in custom filters:
// This example contains a custom filter `|cased`.
// Depending on the runtime value `"case"`, the input is either turned
// into lower case, upper case, or left alone, if the runtime value is undefined.
use std::any::Any;
use askama::{Template, Values};
mod filters {
use super::*;
#[askama::filter_fn]
pub fn cased(value: impl ToString, values: &dyn Values) -> askama::Result<String> {
let value = value.to_string();
let case = askama::get_value(values, "case").ok();
Ok(match case {
Some(Case::Lower) => value.to_lowercase(),
Some(Case::Upper) => value.to_uppercase(),
None => value,
})
}
}
#[derive(Debug, Clone, Copy)]
pub enum Case {
Lower,
Upper,
}
#[test]
fn test_runtime_values_in_custom_filters() {
#[derive(Template)]
#[template(ext = "txt", source = "Hello, {{ user | cased }}!")]
struct MyStruct<'a> {
user: &'a str,
}
// The filter source ("wOrLd") should be written in lower case.
let values: (&str, &dyn Any) = ("case", &Case::Lower);
assert_eq!(
MyStruct { user: "wOrLd" }
.render_with_values(&values)
.unwrap(),
"Hello, world!"
);
// The filter source ("wOrLd") should be written in upper case.
let values: (&str, &dyn Any) = ("case", &Case::Upper);
assert_eq!(
MyStruct { user: "wOrLd" }
.render_with_values(&values)
.unwrap(),
"Hello, WORLD!"
);
// The filter source ("wOrLd") should be written as is.
assert_eq!(
MyStruct { user: "wOrLd" }.render().unwrap(),
"Hello, wOrLd!"
);
}
HTML-safe types
Askama will try to avoid escaping types that generate string representations that do not contain
“HTML-unsafe characters”.
HTML-safe characters are characters that can be used in any context in HTML texts and attributes.
The “unsafe” characters are: <, >, &, " and '.
In order to know which types do not need to be escaped, askama has the marker trait
askama::filters::HtmlSafe, and any type that implements that trait won’t get automatically
escaped in a {{expr}} expression.
By default e.g. all primitive integer types are marked as HTML-safe.
You can also mark your custom type MyStruct as HTML-safe using:
impl askama::filters::HtmlSafe for MyStruct {}
This automatically marks references &MyStruct as HTML-safe, too.
Safe output of custom filters
Say, you have a custom filter | strip that removes all HTML-unsafe characters:
fn strip(s: impl ToString) -> Result<String, askama::Error> {
Ok(s.to_string()
.chars()
.filter(|c| !matches!(c, '<' | '>' | '&' | '"' | '\''))
.collect()
)
}
Then you can also mark the output as safe using askama::filters::Safe:
fn strip(s: impl ToString) -> Result<Safe<String>, askama::Error> {
Ok(Safe(...))
}
There also is askama::filters::MaybeSafe that can be used to mark some output as safe,
if you know that some inputs for our filter will always result in a safe output:
fn as_sign(i: i32) -> Result<MaybeSafe<&'static str>, askama::Error> {
match i.into() {
i if i < 0 => Ok(MaybeSafe::NeedsEscaping("<0")),
i if i > 0 => Ok(MaybeSafe::NeedsEscaping(">0")),
_ => Ok(MaybeSafe::Safe("=0")),
}
}
Working with web-frameworks
Askama’s Template::render() returns Result<String, askama::Error>.
To make this result work in your preferred web-framework, you’ll need to handle both cases:
converting the String to a web-response with the correct Content-Type,
and the Error case to a proper error message.
While in many cases it will be enough to simply convert the Error to
Box<dyn std::error::Error + Send + Sync>usingerr.into_box()orstd::io::Errorusingerr.into_io_error()
it is recommended to use a custom error type. This way you can display the error message in your app’s layout, and you are better prepared for the likely case that your app grows in the future. Maybe you’ll need to access a database and handle errors? Maybe you’ll add multiple languages and you want to localize error messages?
The crates thiserror and displaydoc can be useful to implement this error type.
Simplified alternative
Alternatively, you can use #[derive(askama_web::WebTemplate)]
to automatically implement e.g. actix-web’s Responder, axum’s IntoResponse or warp’s Reply.
The library implements traits for all web-frameworks mentioned down below (and then some),
but it does not stylize error messages.
If you don’t need custom / stylized error messages,
e.g. because you know that your templates won’t have rendering errors, then using
askama_web might work for you, too.
Actix-Web
To convert the String to an HTML response, you can use
Html::new(_).
use actix_web::web::Html;
use actix_web::{Responder, handler};
#[handler]
fn handler() -> Result<impl Responder, AppError> {
…
Ok(Html::new(template.render()?))
}
To implement your own error type, you can use this boilerplate code:
use actix_web::{HttpResponse, Responder};
use actix_web::error::ResponseError;
use actix_web::http::StatusCode;
use actix_web::web::Html;
use askama::Template;
#[derive(Debug, displaydoc::Display, thiserror::Error)]
enum AppError {
/// could not render template
Render(#[from] askama::Error),
}
impl ResponseError for AppError {
fn status_code(&self) -> StatusCode {
match &self {
AppError::Render(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
impl Responder for AppError {
type Body = String;
fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body> {
#[derive(Debug, Template)]
#[template(path = "error.html")]
struct Tmpl { … }
let tmpl = Tmpl { … };
if let Ok(body) = tmpl.render() {
(Html::new(body), self.status_code()).respond_to(req)
} else {
(String::new(), self.status_code()).respond_to(req)
}
}
}
Axum
To convert the String to an HTML response, you can use
Html(_).
use axum::response::{Html, IntoResponse};
async fn handler() -> Result<impl IntoResponse, AppError> {
…
Ok(Html(template.render()?))
}
To implement your own error type, you can use this boilerplate code:
use axum::response::IntoResponse;
use askama::Template;
#[derive(Debug, displaydoc::Display, thiserror::Error)]
enum AppError {
/// could not render template
Render(#[from] askama::Error),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
#[derive(Debug, Template)]
#[template(path = "error.html")]
struct Tmpl { … }
let status = match &self {
AppError::Render(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
let tmpl = Tmpl { … };
if let Ok(body) = tmpl.render() {
(status, Html(body)).into_response()
} else {
(status, "Something went wrong").into_response()
}
}
}
Poem
To convert the String to an HTML response, you can use
Html(_).
use poem::web::Html;
use poem::{IntoResponse, handler};
#[handler]
async fn handler() -> Result<impl IntoResponse, AppError> {
…
Ok(Html(template.render()?))
}
To implement your own error type, you can use this boilerplate code:
use poem::error::ResponseError;
use poem::http::StatusCode;
use poem::web::Html;
use poem::{IntoResponse, Response};
use askama::Template;
#[derive(Debug, displaydoc::Display, thiserror::Error)]
enum AppError {
/// could not render template
Render(#[from] askama::Error),
}
impl ResponseError for AppError {
fn status(&self) -> StatusCode {
match &self {
AppError::Render(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
#[derive(Debug, Template)]
#[template(path = "error.html")]
struct Tmpl { … }
let tmpl = Tmpl { … };
if let Ok(body) = tmpl.render() {
(self.status(), Html(body)).into_response()
} else {
(self.status(), "Something went wrong").into_response()
}
}
}
Rocket
To convert the String to an HTML response, you can use
RawHtml(_).
use rocket::get;
use rocket::response::content::RawHtml;
use rocket::response::Responder;
#[get(…)]
fn handler<'r>() -> Result<impl Responder<'r, 'static>, AppError> {
…
Ok(RawHtml(template.render()?))
}
To implement your own error type, you can use this boilerplate code:
use askama::Template;
use rocket::http::Status;
use rocket::response::content::RawHtml;
use rocket::response::Responder;
use rocket::{Request, Response};
#[derive(Debug, displaydoc::Display, thiserror::Error)]
enum AppError {
/// could not render template
Render(#[from] askama::Error),
}
impl<'r> Responder<'r, 'static> for AppError {
fn respond_to(
self,
request: &'r Request<'_>,
) -> Result<Response<'static>, Status> {
#[derive(Debug, Template)]
#[template(path = "error.html")]
struct Tmpl { … }
let status = match &self {
AppError::Render(_) => Status::InternalServerError,
};
let template = Tmpl { … };
if let Ok(body) = template.render() {
(status, RawHtml(body)).respond_to(request)
} else {
(status, "Something went wrong").respond_to(request)
}
}
}
Warp
To convert the String to an HTML response, you can use
html(_).
use warp::reply::{Reply, html};
fn handler() -> Result<impl Reply, AppError> {
…
Ok(html(template.render()?))
}
To implement your own error type, you can use this boilerplate code:
use http::StatusCode;
use warp::reply::{Reply, Response, html};
#[derive(Debug, displaydoc::Display, thiserror::Error)]
enum AppError {
/// could not render template
Render(#[from] askama::Error),
}
impl Reply for AppError {
fn into_response(self) -> Response {
#[derive(Debug, Template)]
#[template(path = "error.html")]
struct Tmpl { … }
let status = match &self {
AppError::Render(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
let template = Tmpl { … };
if let Ok(body) = template.render() {
with_status(html(body), status).into_response()
} else {
status.into_response()
}
}
}
Performance
Rendering Performance
When rendering an askama template, you should prefer the methods
.render()(to render the content into a new string),.render_into()(to render the content into anfmt::Writeobject, e.g.String) or.write_into()(to render the content into anio::Writeobject, e.g.Vec<u8>)
over .to_string() or format!().
While .to_string() and format!() give you the same result, they generally perform much worse
than askama’s own methods, because fmt::Write uses dynamic methods calls instead of
monomorphised code. On average, expect .to_string() to be 100% to 200% slower than .render().
Faster Rendering of Custom Types
Every type that implements fmt::Display can be used in askama expressions: {{ value }}.
Rendering with fmt::Display can be slow, though, because it uses dynamic methods calls in its
fmt::Formatter argument. To speed up rendering (by a lot, actually),
askama adds the trait FastWritable. For any custom type you want to render,
it has to implement fmt::Display, but if it also implements FastWritable,
then – using autoref-based specialization – the latter implementation is automatically preferred.
To reduce the amount of code duplication, you can let your fmt::Display implementation call
your FastWritable implementation:
use std::fmt::{self, Write};
use askama::{FastWritable, NO_VALUES};
// In a real application, please have a look at
// https://github.com/kdeldycke/awesome-falsehood/blob/690a070/readme.md#human-identity
struct Name<'a> {
forename: &'a str,
surname: &'a str,
}
impl fmt::Display for Name<'_> {
// Because the method simply forwards the call, it should be `inline`.
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// `fmt::Write` has no access to runtime values,
// so simply pass `NO_VALUES`.
self.write_into(f, NO_VALUES)?;
Ok(())
}
}
impl FastWritable for Name<'_> {
fn write_into(
&self,
dest: &mut dyn fmt::Write,
_values: &dyn askama::Values,
) -> askama::Result<()> {
dest.write_str(self.surname)?;
dest.write_str(", ")?;
dest.write_str(self.forename)?;
Ok(())
}
}
#[test]
fn both_implementations_should_render_the_same_text() {
let person = Name {
forename: "Max",
surname: "Mustermann",
};
let mut buf_fmt = String::new();
write!(buf_fmt, "{person}").unwrap();
let mut buf_fast = String::new();
person.write_into(&mut buf_fast, NO_VALUES).unwrap();
assert_eq!(buf_fmt, buf_fast);
assert_eq!(buf_fmt, "Mustermann, Max");
}
Slow Debug Recompilations
If you experience slow compile times when iterating with lots of templates, you can compile Askama’s derive macros with a higher optimization level. This can speed up recompilation times dramatically.
Add the following to Cargo.toml or .cargo/config.toml:
[profile.dev.package.askama_derive]
opt-level = 3
This may affect clean compile times in debug mode, but incremental compiles will be faster.
With a nightly compiler, you can additionally try using the parallel frontend by
adding the following lines to your .cargo/config.toml:
[build]
rustflags = ["-Z", "threads=16"]
This will mostly show noticeable improvements when you have a single large crate with many askama templates.
Profile-Guided Optimization (PGO)
To optimize askama’s performance, you can compile your application with Profile-Guided Optimization. According to the tests, PGO can improve the library performance by 15%.
Upgrading to new versions
This file only lists breaking changes you need to be aware of when you upgrade to a new askama version. Please see our release notes to get a list of all changes and improvements that might be useful to you.
From askama v0.15 to askama v0.16
-
Variable creation without value cannot be done with
let/setanymore. You need to use the newdecl/declareinstead:{% decl variable_without_value %} -
Duplicated blocks will now error and prevent compilation instead of emitting a warning.
From askama v0.14 to askama v0.15
-
The MSRV of this release is 1.88.
-
Filter functions now need to have the
filter_fnproc-macro used on them. So if you had:pub fn to_string(s: impl ToString, _: &dyn Values) -> Result<String> { Ok(s.to_string()) }It now becomes:
#[askama::filter_fn] pub fn to_string(s: impl ToString, _: &dyn Values) -> Result<String> { Ok(s.to_string()) } -
Variables declared in the templates cannot be named
calleranymore.
From askama v0.13 to askama v0.14
-
The MSRV of this release is 1.83.
-
When assigning a new variable (
{% let var = … %}) with a local variable was value, it is moved or copied, not referenced. -
Try expressions (
{{ expr? }}) are not placed behind a reference. -
FastWritableimplementations have access to runtime values. -
Custom filters have access to runtime values, and must add a second
&dyn askama::Valuesargument as in the example. -
|uniqueis a built-in filter;|titlecaseis an alias for|title.
From askama v0.12 to askama v0.13
A blog post summarizing changes and also explaining the merge of rinja and askama is
available here.
List of breaking changes:
-
The MSRV of this release is 1.81.
-
The integration crates were removed. Instead of depending on e.g.
askama_axum/askama_axum, please usetemplate.render()to render to aResult<String, askama::Error>.Use e.g.
.map_err(|err| err.into_io_error())?if your web-framework expectsstd::io::Errors, orerr.into_box()if it expectsBox<dyn std::error::Error + Send + Sync>.Please read the documentation of your web-framework how to turn a
Stringinto a web-response. -
The fields
Template::EXTENSIONandTemplate::MIME_TYPEwere removed. -
You may not give variables a name starting with
__askama, or the name of a rust keyword. -
#[derive(Template)]cannot be used withunions. -
|linebreaks,|linebreaksbrand|paragraphbreaksescape their input automatically. -
|jsondoes not prettify its output by default anymore. Use e.g.|json(2)for readable output. -
The binary operators
|,&and^are now calledbitor,bitandandxor, resp. -
The feature
"humansize"was removed. The filter|humansizeis always available. -
The feature
"serde-json"is now called"serde_json". -
The feature
"markdown"was removed. Usecomrakdirectly. -
The feature
"serde-yaml"was removed. Use e.g.yaml-rust2directly.
From rinja v0.3 to askama v0.13
-
The MSRV of this release is 1.81.
-
The projects rinja and askama were re-unified into one project. You need to replace instances of
rinjawithaskama, e.g.-use rinja::Template; +use askama::Template;[dependencies] -rinja = "0.3.5" +askama = "0.13.0" -
The integration crates were removed. Instead of depending on e.g.
rinja_axum/askama_axum, please usetemplate.render()to render to aResult<String, askama::Error>.Use e.g.
.map_err(|err| err.into_io_error())?if your web-framework expectsstd::io::Errors, orerr.into_box()if it expectsBox<dyn std::error::Error + Send + Sync>.Please read the documentation of your web-framework how to turn a
Stringinto a web-response. -
The fields
Template::EXTENSIONandTemplate::MIME_TYPEwere removed. -
The feature
"humansize"was removed. The filter|humansizeis always available. -
You may not give variables a name starting with
__rinja, or the name of a rust keyword. -
#[derive(Template)]cannot be used withunions.
From rinja v0.2 to rinja v0.3
- You should be able to upgrade to v0.3 without changes.
From askama v0.12 to rinja v0.2
Have a look at our blog posts that highlight some of the best features of our releases, and give you more in-dept explanations: docs.rs switching jinja template framework from tera to rinja.
-
The MSRV of this release is 1.71.
-
You need to replace instances of
askamawithrinja, e.g.-use askama::Template; +use rinja::Template;[dependencies] -askama = "0.12.1" +rinja = "0.2.0" -
|linebreaks,|linebreaksbrand|paragraphbreaksescape their input automatically. -
|jsondoes not prettify its output by default anymore. Use e.g.|json(2)for readable output. -
The binary operators
|,&and^are now calledbitor,bitandandxor, resp. -
Filter
as_refis now justref -
The feature
"serde-json"is now called"serde_json". -
The feature
"markdown"was removed. Usecomrakdirectly. -
The feature
"serde-yaml"was removed. Use e.g.yaml-rust2directly.
From askama v0.11 to askama v0.12
-
The magic
_parentfield to access&**selfwas removed. -
Integration implementations do not need an
extargument anymore. -
The
ironintegration was removed.