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

This was very appealing from the very first moment. You can keep all your templates in your root folder, for example templates/home.jinja.

{% block content %}
    <h1>Hello, {{email}}</h1>
    {% if let Some(name) = name %}
        <h1>Hello, {{name}}</h1>
    {% else %}
    {% endif %}
{% endblock %}

And then you can use your template with a struct in your project

use askama::Template;

#[derive(Template)]
#[template(path="home.jinja")]
pub struct HomeTemplate {
    // some users might not have one upon sign-up
    name: Option<String>,
    // email is required
    email: String,
}

What’s really cool is that you can even use rust syntax inside of templates

{% block content %}
    {% if let Some(name) = name %}
        <h1>Hello, {{name}}</h1>
    {% else %}
        <h1>Hello, {{email}}</h1>
    {% endif %}
{% endblock %}

I love rust match arms, you can also use those in Askama templates. In Ulry I have to render different components depending on the value of a certain enum

#[derive(Debug, PartialEq, Eq)]
pub enum LinkNote {
    /// note is a valid HN link
    HN(String),
    /// note is a valid link
    Link(String),
    /// general note
    General(String),
}

LinkNote models three different kind of notes that you can attach to a link, here’s how I can use this in my template.

{% if let Some(note) = link.note %}
    {% match note %}
        {% when LinkNote::HN with (url) %}
            <a href="{{url}}"><p>hn</p></a>
        {% when LinkNote::Link with (url) %}
            <a href="{{url}}"><p>link</p></a>
        {% else %}
            <p>note</p>
    {% endmatch %}
{% endif %}

These are just some simple examples of what you can do with Askama templates, if you want to find out more they have a pretty good book that you can take a look at.