[package]
name = "use-minijinja"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
axum = "0.8.8"
minijinja = "2.3.1"
tokio = { version = "1.50.0", features = ["full"] }
[dev-dependencies]
headers = "0.4.1"
http-body-util = "0.1.3"
tower = { version = "0.5.3", features = ["util"] }
use axum::extract::State;
use axum::http::StatusCode;
use axum::{Router, response::Html, routing::get};
use minijinja::{Environment, context};
use std::sync::Arc;
struct AppState {
env: Environment<'static>,
}
#[tokio::main]
async fn main() {
let app = create_router();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on http://{}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
}
fn create_router() -> Router {
let mut env = Environment::new();
env.add_template("main", include_str!("../templates/main.html"))
.unwrap();
let app_state = Arc::new(AppState { env });
Router::new()
.route("/", get(main_page))
.with_state(app_state)
}
async fn main_page(State(state): State<Arc<AppState>>) -> Result<Html<String>, StatusCode> {
let template = state.env.get_template("main").unwrap();
let rendered = template
.render(context! {
title => "Mini Jinja",
welcome_text => "Hello World!",
})
.unwrap();
Ok(Html(rendered))
}
#[cfg(test)]
mod tests;
#![allow(unused)]
fn main() {
use super::*;
use axum::{
body::Body,
http::{Request, StatusCode},
};
use http_body_util::BodyExt;
use tower::ServiceExt;
#[tokio::test]
async fn test_main() {
let response = create_router()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let content_type = response.headers().get("content-type").unwrap();
assert_eq!(content_type.to_str().unwrap(), "text/html; charset=utf-8");
let body = response.into_body();
let bytes = body.collect().await.unwrap().to_bytes();
let html = String::from_utf8(bytes.to_vec()).unwrap();
assert!(html.contains("<h1>Mini Jinja</h1>"));
assert!(html.contains("<p>Hello World!</p>"));
}
}