FAQ - Help and questions

How do I render HTML templates in axum with minijinja?

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

Short answer

Create one minijinja Environment at start-up, add your templates, share it through State in an Arc, and return Html(template.render(context!{...})). Names ending in .html are escaped automatically, so user input such as a script tag is shown as text and not run.

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; minijinja 2.24.0

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

#1

Answer#

minijinja renders Jinja-style templates at run time. Build the Environment once and share it:

src/main.rsrust
use axum::{body::{to_bytes, Body}, extract::{Path, State}, http::{Request, StatusCode}, response::Html, routing::get, Router};
use minijinja::{context, Environment};
use std::sync::Arc;
use tower::ServiceExt;

type Templates = Arc<Environment<'static>>;

async fn hello(State(t): State<Templates>, Path(name): Path<String>) -> Result<Html<String>, StatusCode> {
    let page = t.get_template("hello.html").map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    page.render(context! { name, items => vec!["a", "b"] })
        .map(Html)
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}

#[tokio::main]
async fn main() {
    let mut env = Environment::new();
    env.add_template("hello.html", "<h1>Hello {{ name }}</h1><ul>{% for i in items %}<li>{{ i }}</li>{% endfor %}</ul>").unwrap();
    let app = Router::new().route("/hello/{name}", get(hello)).with_state(Arc::new(env));
    for uri in ["/hello/Ada", "/hello/%3Cscript%3Ealert(1)%3C%2Fscript%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();
        println!("{}", String::from_utf8_lossy(&body));
    }
}
text
<h1>Hello Ada</h1><ul><li>a</li><li>b</li></ul>
<h1>Hello &lt;script&gt;alert(1)&lt;&#x2f;script&gt;</h1><ul><li>a</li><li>b</li></ul>

The second request put a <script> tag in the URL. The output shows it escaped (&lt;script&gt;), so a browser would display the text and not run it. Escaping was applied because the template is named hello.html.

Cargo.tomltoml
minijinja = "2.24.0"

In a real project keep the templates as files and load them when the program starts (see the crate documentation for loading templates from a folder); the strings above only keep the example in one file.

Common mistakes#

  • Marking user-supplied text as safe to skip escaping. Do that only for HTML you generated yourself.
  • Creating a new Environment inside the handler for every request: it parses the templates each time.

Is there a compile-time alternative?#

Yes: the askama crate checks templates when the program is compiled. See the thread on askama.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet