Askama

Documentation Latest version Build Status Chat

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, or read the book.

"Pretty exciting. I would love to use this already." -- Armin Ronacher, creator of Jinja

All feedback welcome. Feel free to file bugs, requests for documentation and any other feedback to the issue tracker or tweet me.

Askama was created by and is maintained by Dirkjan Ochtman. If you are in a position to support ongoing maintenance and further development or use it in a for-profit context, please consider supporting my open source work on Patreon.

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
  • Optional built-in support for Actix, Axum, Gotham, Mendes, Rocket, tide, and warp web frameworks
  • Debugging features to assist you in template development
  • Templates must be valid UTF-8 and produce UTF-8 when rendered
  • IDE support available in JetBrains products
  • Works on stable Rust

Supported in templates

  • Template inheritance
  • Loops, if/else statements and include support
  • Macro support
  • Variables (no mutability allowed)
  • Some 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 section [dependencies]
askama = "0.12.1"

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.

Using integrations

To use one of the integrations, with axum as an example:

First, add this to your Cargo.toml instead:

# in section [dependencies]
askama_axum = "0.4.0"

Then, import from askama_axum instead of askama:

#![allow(unused)]
fn main() {
use askama_axum::Template;
}

This enables the implementation for axum's IntoResponse trait, so an instance of the template can be returned as a response.

For other integrations, import and use their crate accordingly.

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.

#![allow(unused)]
fn main() {
#[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 (as 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 a templates directory next to your Cargo.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 with source.

    #![allow(unused)]
    fn main() {
    #[derive(Template)]
    #[template(path = "hello.html")]
    struct HelloTemplate<'a> { ... }
    }
  • source (as 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. If source is specified, ext must also be specified (see below). Cannot be used together with path.

    #![allow(unused)]
    fn main() {
    #[derive(Template)]
    #[template(source = "Hello {{ name }}")]
    struct HelloTemplate<'a> {
        name: &'a str,
    }
    }
  • ext (as 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 with path.

    #![allow(unused)]
    fn main() {
    #[derive(Template)]
    #[template(source = "Hello {{ name }}", ext = "txt")]
    struct HelloTemplate<'a> {
        name: &'a str,
    }
    }
  • print (as print = "code"): enable debugging by printing nothing (none), the parsed syntax tree (ast), the generated code (code) or all for both. The requested data will be printed to stdout at compile time.

    #![allow(unused)]
    fn main() {
    #[derive(Template)]
    #[template(path = "hello.html", print = "all")]
    struct HelloTemplate<'a> { ... }
    }
  • escape (as 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.

    #![allow(unused)]
    fn main() {
    #[derive(Template)]
    #[template(path = "hello.html", escape = "none")]
    struct HelloTemplate<'a> { ... }
    }
  • syntax (as syntax = "foo"): set the syntax name for a parser defined in the configuration file. The default syntax , "default", is the one provided by Askama.

    #![allow(unused)]
    fn main() {
    #[derive(Template)]
    #[template(path = "hello.html", syntax = "foo")]
    struct HelloTemplate<'a> { ... }
    }
  • config (as config = "config_file_path"): set the path for the config file to be used. The path is interpreted as relative to your crate root.

    #![allow(unused)]
    fn main() {
    #[derive(Template)]
    #[template(path = "hello.html", config = "config.toml")]
    struct HelloTemplate<'a> { ... }
    }

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:

#![allow(unused)]
fn main() {
#[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:

#![allow(unused)]
fn main() {
impl < 'a > ::askama::Template for HelloTemplate< 'a > {
    fn render_into(&self, writer: &mut ::std::fmt::Write) -> ::askama::Result<()> {
        write!(
            writer,
            "Hello, {expr0}!",
            expr0 = &::askama::MarkupDisplay::from(&self.name),
        )?;
        Ok(())
    }
    fn extension() -> Option<&'static str> {
        Some("html")
    }
}
impl < 'a > ::std::fmt::Display for HelloTemplate< 'a > {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        ::askama::Template::render_into(self, f).map_err(|_| ::std::fmt::Error {})
    }
}
}

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). 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"

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", 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 behaviour, you can set whitespace to "minimize".

To be noted: you can also configure whitespace directly into the template derive proc macro:

#![allow(unused)]
fn main() {
#[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.

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. 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.

Template Syntax

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:

#![allow(unused)]
fn main() {
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() %}

{% let val -%}
{% if len == 0 -%}
  {% let val = "foo" -%}
{% else -%}
  {% let val = name -%}
{% endif -%}
{{ val }}

Like Rust, Askama also supports shadowing variables.

{% let foo = "bar" %}
{{ foo }}

{% let foo = "baz" %}
{{ foo }}

For compatibility with Jinja, set can be used in place of let.

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 -%}
  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:

  1. Inline (-, +, ~)
  2. Derive (#[template(whitespace = "suppress")])
  3. 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.

  1. Suppress (-)
  2. Minimize (~)
  3. Preserve (+)

Functions

There are several ways that functions can be called within templates, depending on where the function definition resides. These are:

  • Template struct fields
  • 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:

#![allow(unused)]
fn main() {
#[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 behaviour 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:

#![allow(unused)]
fn main() {
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:

#![allow(unused)]
fn main() {
// 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:

#![allow(unused)]
fn main() {
// src/templates/my_template.rs

#[derive(Template)]
#[template(source = "{{ crate::templates::utils::foo(123) }}", ext = "txt")]
struct MyTemplate;
}

Struct / trait implementations

Finally, we can invoke functions that are implementation methods of our template struct, by referencing Self (note the uppercase S) as the path, before calling our function:

#![allow(unused)]
fn main() {
#[derive(Template)]
#[template(source = "{{ Self::foo(self, 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)
  }
}
}

If the implemented method requires a reference to the struct itself, such as is demonstrated in the above example, we can pass self (note the lowercase s) as the first argument.

Similarly, using the Self path, we can also call any method belonging to a trait that has been implemented for our template struct:

#![allow(unused)]
fn main() {
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)
  }
}
}

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>
  {% call 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.

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(),
        "&#x2f;&#x2f; my &lt;html&gt; is &quot;unsafe&quot; &amp; \
         should be &#x27;escaped&#x27;"
    );
}

Control structures

For

Loop over each item in an iterator. For example:

<h1>Users</h1>
<ul>
{% for user in users %}
  <li>{{ user.name|e }}</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
{% 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 %}

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 can optionally contain some whitespace (but no other literal content), followed by a number of when blocks and an optional else block. Each when block must name a list of matches ((val)), optionally introduced with a variant name. The else block is equivalent to matching on _ (matching anything).

Struct-like enum variants are supported from version 0.8, with the list of matches surrounded by curly braces instead ({ field }). New names for the fields can be specified after a colon in the list of matches ({ field: val }).

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: {{ 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 precedence order as the Rust compiler. Expressions can be grouped using parentheses. The HTML special characters &, < and > will be replaced with their character entities unless the escape mode is disabled for a template. Methods can be called on variables that are in scope, including self.

{{ 3 * 4 / 2 }}
{{ 26 / 2 % 7 }}
{{ 3 % 2 * 6 }}
{{ 1 * 2 + 4 }}
{{ 11 - 15 / 3 }}
{{ 4 + 5 % 3 }}
{{ 4 | 2 + 5 & 2 }}

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.

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.

#![allow(unused)]
fn main() {
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")
}

See the example render in place 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. Including self does not work, see #105 and #220 .

#![allow(unused)]
fn main() {
use askama::Template;

#[derive(Template)]
#[template(source = r#"
//! {% for item in children %}
   {{ item }}
{% endfor %}
"#, ext = "html", escape = "none")]
struct Item<'a> {
    name: &'a str,
    children: &'a [Item<'a>],
}
}

Macros

You can define macros within your template by using {% macro name(args) %}, ending with {% endmacro %}.

You can then call it with {% call name(args) %}:

{% macro heading(arg) %}

<h1>{{arg}}</h1>

{% endmacro %}

{% call heading(s) %}

You can place macros in a separate file and use them in your templates by using {% import %}:

{%- import "macro.html" as scope -%}

{% call scope::heading(s) %}

You can optionally specify the name of the macro in endmacro:

{% macro heading(arg) %}<p>{{arg}}</p>{% endmacro heading %}

You can also specify arguments by their name (as defined in the macro):

{% macro heading(arg, bold) %}

<h1>{{arg}} <b>{{bold}}</b></h1>

{% endmacro %}

{% call heading(bold="something", arg="title") %}

You can use whitespace characters around =:

{% call heading(bold = "something", arg = "title") %}

You can mix named and non-named arguments when calling a macro:

{% call heading("title", bold="something") %}

However please note than named arguments must always come last.

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 %}

{% call 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:

{% call heading("something", arg3="b", arg4="ah", arg2="title") %}
{# Equivalent of: #}
{% call heading("something", "title", "b", arg4="ah") %}

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:

#![allow(unused)]
fn main() {
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) }}

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. Note that the pipe symbol must not be surrounded by spaces; otherwise, it will be interpreted as the BitOr operator. 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).

Table of contents

Built-In Filters

abs

Returns the absolute value.

{{ -2|abs }}

Output:

2

as_ref

Creates a reference to the given argument.

{{ "a"|as_ref }}
{{ self.x|as_ref }}

will become:

&"a"
&self.x

capitalize

Capitalize a value. The first character will be uppercase, all others lowercase:

{{ "hello"|capitalize }}

Output:

Hello

center

Centers the value in a field of a given width:

-{{ "a"|center(5) }}-

Output:

-  a  -

escape | e

Escapes HTML characters in strings:

{{ "Escape <>&"|e }}

Output:

Escape &lt;&gt;&amp;

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 &lt;&gt;&amp;
Escape &lt;&gt;&amp;

filesizeformat

Returns adequate string representation (in KB, ..) of number of bytes:

{{ 1000|filesizeformat }}

Output:

1 KB

fmt

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

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

Indent newlines with width spaces.

{{ "hello\nfoo\nbar"|indent(4) }}

Output:

hello
    foo
    bar

join

Joins iterable into a string separated by provided argument.

array = &["foo", "bar", "bazz"]
{{ array|join(", ") }}

Output:

foo, bar, bazz

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

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

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

Converts to lowercase.

{{ "HELLO"|lower }}

Output:

hello

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>

trim

Strip leading and trailing whitespace.

{{ " hello "|trim }}

Output:

hello

truncate

Limit string length, appends '...' if truncated.

{{ "hello"|truncate(2) }}

Output:

he...

upper | uppercase

Converts to uppercase.

{{ "hello"|upper }}

Output:

HELLO

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.11.2", features = "serde-json" }

json | tojson

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>

Custom Filters

To define your own filters, simply have a module named filters in scope of the context deriving a Template impl and define the filters as functions within this module. The functions must have at least one argument and the return type must be ::askama::Result<T>. Although there are no restrictions on T for a single filter, the final result of a chain of filters must implement Display.

The arguments to the filters are passed as follows. The first argument corresponds to the expression they are applied to. Subsequent arguments, if any, must be given directly when calling the filter. The first argument may or may not be a reference, depending on the context in which the filter is called. To abstract over ownership, consider defining your argument as a trait bound. For example, the trim built-in filter accepts any value implementing Display. Its signature is similar to fn trim(s: impl std::fmt::Display) -> ::askama::Result<String>.

Note that built-in filters have preference over custom filters, so, in case of name collision, the built-in filter is applied.

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
    pub fn myfilter<T: std::fmt::Display>(s: T) -> ::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
    pub fn myfilter<T: std::fmt::Display>(s: T, 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");
}

Integrations

Rocket integration

In your template definitions, replace askama::Template with askama_rocket::Template.

Enabling the with-rocket feature appends an implementation of Rocket's Responder trait for each template type. This makes it easy to trivially return a value of that type in a Rocket handler. See the example from the Askama test suite for more on how to integrate.

In case a run-time error occurs during templating, a 500 Internal Server Error Status value will be returned, so that this can be further handled by your error catcher.

Actix-web integration

In your template definitions, replace askama::Template with askama_actix::Template.

Enabling the with-actix-web feature appends an implementation of Actix-web's Responder trait for each template type. This makes it easy to trivially return a value of that type in an Actix-web handler. See the example from the Askama test suite for more on how to integrate.

Axum integration

In your template definitions, replace askama::Template with askama_axum::Template.

Enabling the with-axum feature appends an implementation of Axum's IntoResponse trait for each template type. This makes it easy to trivially return a value of that type in a Axum handler. See the example from the Askama test suite for more on how to integrate.

In case of a run-time error occurring during templating, the response will be of the same signature, with a status code of 500 Internal Server Error, mime */*, and an empty Body. This preserves the response chain if any custom error handling needs to occur.

Warp integration

In your template definitions, replace askama::Template with askama_warp::Template.

Enabling the with-warp feature appends an implementation of Warp's Reply trait for each template type. This makes it simple to return a template from a Warp filter. See the example from the Askama test suite for more on how to integrate.

Performance

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:

#![allow(unused)]
fn main() {
[profile.dev.package.askama_derive]
opt-level = 3
}

This may affect clean compile times in debug mode, but incremental compiles will be faster.

Template Expansion

This chapter will explain how the different parts of the templates are translated into Rust code.

⚠️ Please note that the generated code might change in the future so the following examples might not be up-to-date.

Basic explanations

When you add #[derive(Template)] and #[template(...)] on your type, the Template derive proc-macro will then generate an implementation of the askama::Template trait which will be a Rust version of the template.

It will also implement the std::fmt::Display trait on your type which will internally call the askama::Template trait.

Let's take a small example:

#![allow(unused)]
fn main() {
#[derive(Template)]
#[template(source = "{% set x = 12 %}", ext = "html")]
struct Mine;
}

will generate:

#![allow(unused)]
fn main() {
impl ::askama::Template for YourType {
    fn render_into(
        &self,
        writer: &mut (impl ::std::fmt::Write + ?Sized),
    ) -> ::askama::Result<()> {
        let x = 12;
        ::askama::Result::Ok(())
    }
    const EXTENSION: ::std::option::Option<&'static ::std::primitive::str> = Some(
        "html",
    );
    const SIZE_HINT: ::std::primitive::usize = 0;
    const MIME_TYPE: &'static ::std::primitive::str = "text/html; charset=utf-8";
}

impl ::std::fmt::Display for YourType {
    #[inline]
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        ::askama::Template::render_into(self, f).map_err(|_| ::std::fmt::Error {})
    }
}
}

For simplicity, we will only keep the content of the askama::Template::render_into function from now on.

Text content

If you have "text content" (for example HTML) in your template:

<h1>{{ title }}</h1>

It will generate it like this:

#![allow(unused)]
fn main() {
writer
    .write_fmt(
        format_args!(
            "<h1>{0}</h1>",
            &::askama::MarkupDisplay::new_unsafe(&(self.title), ::askama::Html),
        ),
    )?;
::askama::Result::Ok(())
}

About MarkupDisplay: we need to use this type in order to prevent generating invalid HTML. Let's take an example: if title is "<a>" and we display it as is, in the generated HTML, you won't see <a> but instead a new HTML element will be created. To prevent this, we need to escape some characters.

In this example, <a> will become &lt;a&gt;. And this is why there is the safe builtin filter, in case you want it to be displayed as is.

Variables

Variables creation

If you create a variable in your template, it will be created in the generated Rust code as well. For example:

{% set x = 12 %}
{% let y = x + 1 %}

will generate:

#![allow(unused)]
fn main() {
let x = 12;
let y = x + 1;
::askama::Result::Ok(())
}

Variables usage

By default, variables will reference a field from the type on which the askama::Template trait is implemented:

{{ y }}

This template will expand as follows:

#![allow(unused)]
fn main() {
writer
    .write_fmt(
        format_args!(
            "{0}",
            &::askama::MarkupDisplay::new_unsafe(&(self.y), ::askama::Html),
        ),
    )?;
::askama::Result::Ok(())
}

This is why if the variable is undefined, it won't work with Askama and why we can't check if a variable is defined or not.

You can still access constants and statics by using paths. Let's say you have in your Rust code:

#![allow(unused)]
fn main() {
const FOO: u32 = 0;
}

Then you can use them in your template by referring to them with a path:

{{ crate::FOO }}{{ super::FOO }}{{ self::FOO }}

It will generate:

#![allow(unused)]
fn main() {
writer
    .write_fmt(
        format_args!(
            "{0}{1}{2}",
            &::askama::MarkupDisplay::new_unsafe(&(crate::FOO), ::askama::Html),
            &::askama::MarkupDisplay::new_unsafe(&(super::FOO), ::askama::Html),
            &::askama::MarkupDisplay::new_unsafe(&(self::FOO), ::askama::Html),
        ),
    )?;
::askama::Result::Ok(())
}

(Note: crate:: is to get an item at the root level of the crate, super:: is to get an item in the parent module and self:: is to get an item in the current module.)

You can also access items from the type that implements Template as well using as Self::, it'll use the same logic.

Control blocks

if/else

The generated code can be more complex than expected, as seen with if/else conditions:

{% if x == "a" %}
gateau
{% else %}
tarte
{% endif %}

It will generate:

#![allow(unused)]
fn main() {
if *(&(self.x == "a") as &bool) {
    writer.write_str("gateau")?;
} else {
    writer.write_str("tarte")?;
}
::askama::Result::Ok(())
}

Very much as expected except for the &(self.x == "a") as &bool. Now about why the as &bool is needed:

The following syntax *(&(...) as &bool) is used to trigger Rust's automatic dereferencing, to coerce e.g. &&&&&bool to bool. First &(...) as &bool coerces e.g. &&&bool to &bool. Then *(&bool) finally dereferences it to bool.

In short, it allows to fallback to a boolean as much as possible, but it also explains why you can't do:

{% set x = "a" %}
{% if x %}
    {{ x }}
{% endif %}

Because it fail to compile because:

error[E0605]: non-primitive cast: `&&str` as `&bool`

if let

{% if let Some(x) = x %}
    {{ x }}
{% endif %}

will generate:

#![allow(unused)]
fn main() {
if let Some(x) = &(self.x) {
    writer
        .write_fmt(
            format_args!(
                "{0}",
                &::askama::MarkupDisplay::new_unsafe(&(x), ::askama::Html),
            ),
        )?;
}
}

Loops

{% for user in users %}
    {{ user }}
{% endfor %}

will generate:

#![allow(unused)]
fn main() {
{
    let _iter = (&self.users).into_iter();
    for (user, _loop_item) in ::askama::helpers::TemplateLoop::new(_iter) {
        writer
            .write_fmt(
                format_args!(
                    "\n    {0}\n",
                    &::askama::MarkupDisplay::new_unsafe(&(user), ::askama::Html),
                ),
            )?;
    }
}
::askama::Result::Ok(())
}

Now let's see what happens if you add an else condition:

{% for user in x if x.len() > 2 %}
    {{ user }}
{% else %}
    {{ x }}
{% endfor %}

Which generates:

#![allow(unused)]
fn main() {
{
    let mut _did_loop = false;
    let _iter = (&self.users).into_iter();
    for (user, _loop_item) in ::askama::helpers::TemplateLoop::new(_iter) {
        _did_loop = true;
        writer
            .write_fmt(
                format_args!(
                    "\n    {0}\n",
                    &::askama::MarkupDisplay::new_unsafe(&(user), ::askama::Html),
                ),
            )?;
    }
    if !_did_loop {
        writer
            .write_fmt(
                format_args!(
                    "\n    {0}\n",
                    &::askama::MarkupDisplay::new_unsafe(
                        &(self.x),
                        ::askama::Html,
                    ),
                ),
            )?;
    }
}
::askama::Result::Ok(())
}

It creates a _did_loop variable which will check if we entered the loop. If we didn't (because the iterator didn't return any value), it will enter the else condition by checking if !_did_loop {.

We can extend it even further if we add an if condition on our loop:

{% for user in users if users.len() > 2 %}
    {{ user }}
{% else %}
    {{ x }}
{% endfor %}

which generates:

#![allow(unused)]
fn main() {
{
    let mut _did_loop = false;
    let _iter = (&self.users).into_iter();
    let _iter = _iter.filter(|user| -> bool { self.users.len() > 2 });
    for (user, _loop_item) in ::askama::helpers::TemplateLoop::new(_iter) {
        _did_loop = true;
        writer
            .write_fmt(
                format_args!(
                    "\n    {0}\n",
                    &::askama::MarkupDisplay::new_unsafe(&(user), ::askama::Html),
                ),
            )?;
    }
    if !_did_loop {
        writer
            .write_fmt(
                format_args!(
                    "\n    {0}\n",
                    &::askama::MarkupDisplay::new_unsafe(
                        &(self.x),
                        ::askama::Html,
                    ),
                ),
            )?;
    }
}
::askama::Result::Ok(())
}

It generates an iterator but filters it based on the if condition (users.len() > 2). So once again, if the iterator doesn't return any value, we enter the else condition.

Of course, if you only have a if and no else, the generated code is much shorter:

{% for user in users if users.len() > 2 %}
    {{ user }}
{% endfor %}

Which generates:

#![allow(unused)]
fn main() {
{
    let _iter = (&self.users).into_iter();
    let _iter = _iter.filter(|user| -> bool { self.users.len() > 2 });
    for (user, _loop_item) in ::askama::helpers::TemplateLoop::new(_iter) {
        writer
            .write_fmt(
                format_args!(
                    "\n    {0}\n",
                    &::askama::MarkupDisplay::new_unsafe(&(user), ::askama::Html),
                ),
            )?;
    }
}
::askama::Result::Ok(())
}

Filters

Example of using the abs built-in filter:

{{ -2|abs }}

Which generates:

#![allow(unused)]
fn main() {
writer
    .write_fmt(
        format_args!(
            "{0}",
            &::askama::MarkupDisplay::new_unsafe(
                &(::askama::filters::abs(-2)?),
                ::askama::Html,
            ),
        ),
    )?;
::askama::Result::Ok(())
}

The filter is called with -2 as first argument. You can add further arguments to the call like this:

{{ "a"|indent(4) }}

Which generates:

#![allow(unused)]
fn main() {
writer
    .write_fmt(
        format_args!(
            "{0}",
            &::askama::MarkupDisplay::new_unsafe(
                &(::askama::filters::indent("a", 4)?),
                ::askama::Html,
            ),
        ),
    )?;
::askama::Result::Ok(())
}

No surprise there, 4 is added after "a". Now let's check when we chain the filters:

{{ "a"|indent(4)|capitalize }}

Which generates:

#![allow(unused)]
fn main() {
writer
    .write_fmt(
        format_args!(
            "{0}",
            &::askama::MarkupDisplay::new_unsafe(
                &(::askama::filters::capitalize(
                    &(::askama::filters::indent("a", 4)?),
                )?),
                ::askama::Html,
            ),
        ),
    )?;
::askama::Result::Ok(())
}

As expected, capitalize's first argument is the value returned by the indent call.

Macros

This code:

{% macro heading(arg) %}
<h1>{{arg}}</h1>
{% endmacro %}

{% call heading("title") %}

generates:

#![allow(unused)]
fn main() {
{
    let (arg) = (("title"));
    writer
        .write_fmt(
            format_args!(
                "\n<h1>{0}</h1>\n",
                &::askama::MarkupDisplay::new_unsafe(&(arg), ::askama::Html),
            ),
        )?;
}
::askama::Result::Ok(())
}

As you can see, the macro itself isn't present in the generated code, only its internal code is generated as well as its arguments.