Answer#
minijinja renders Jinja-style templates at run time. Build the Environment once and share it:
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));
}
}<h1>Hello Ada</h1><ul><li>a</li><li>b</li></ul>
<h1>Hello <script>alert(1)</script></h1><ul><li>a</li><li>b</li></ul>The second request put a <script> tag in the URL. The output shows it escaped (<script>), so a browser would display the text and not run it. Escaping was applied because the template is named hello.html.
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
Environmentinside the handler for every request: it parses the templates each time.
Related questions#
Is there a compile-time alternative?#
Yes: the askama crate checks templates when the program is compiled. See the thread on askama.
Sources#
- minijinja documentation: https://docs.rs/minijinja/2.24.0/minijinja/ (read 2026-12-05)