FAQ - Help and questions

How do I use askama templates in axum, and what do its compile errors mean?

#axum#templates#askama#htmlpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Write the HTML in a file under templates/, derive Template on a struct with #[template(path = "...")], and call render() in the handler. The template is checked against the struct when the program is compiled, so a misspelled field is a compile error, not a blank spot on a live page.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot; askama 0.14.0

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

askama turns each template into Rust code at compile time. The template file:

templates/hello.htmlhtml
<h1>Hello {{ name }}</h1>

and the handler:

src/main.rsrust
use askama::Template;
use axum::{body::{to_bytes, Body}, extract::Path, http::{Request, StatusCode}, response::Html, routing::get, Router};
use tower::ServiceExt;

#[derive(Template)]
#[template(path = "hello.html")] // templates/hello.html, relative to the crate root
struct Hello {
    name: String,
}

async fn hello(Path(name): Path<String>) -> Result<Html<String>, StatusCode> {
    Hello { name }.render().map(Html).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/hello/{name}", get(hello));
    for uri in ["/hello/Ada", "/hello/%3Cb%3Ebold%3C%2Fb%3E"] {
        let res = app.clone().oneshot(Request::get(uri).body(Body::empty()).unwrap()).await.unwrap();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        print!("{}", String::from_utf8_lossy(&body));
    }
}
text
<h1>Hello Ada</h1><h1>Hello &#60;b&#62;bold&#60;/b&#62;</h1>

The plain name was printed as is. The name <b>bold</b> came out as &#60;b&#62;bold&#60;/b&#62;: askama escapes values in .html templates by default.

A misspelled variable stops the build. With {{ nam }} in the template, cargo check reports:

text
error[E0609]: no field `nam` on type `&Hello`
 --> examples\f24.rs:3:10
  |
3 | #[derive(Template)]
  |          ^^^^^^^^ unknown field
...
Cargo.tomltoml
askama = "0.14.0"

Common mistakes#

  • Expecting a template edit to show without building: the template is part of the compiled program, so the program must be built again.
  • Expecting run-time reloading in production. If non-programmers must change templates without a rebuild, use a run-time engine (see the minijinja thread).

Which one should I pick?#

Compile-time checking (askama) finds mistakes early; run-time loading (minijinja) allows changing templates without compiling. Both escape HTML by default for .html names.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet