generated from alecodes/base-template
feat: add basic template functionality
This commit is contained in:
parent
b6c909f6f4
commit
6bf3947df3
5 changed files with 52 additions and 3 deletions
28
src/main.rs
28
src/main.rs
|
|
@ -1,10 +1,28 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Html;
|
||||
use axum::routing::get;
|
||||
use axum::Router;
|
||||
use minijinja::{context, Environment};
|
||||
|
||||
struct AppState {
|
||||
tmpl_env: Environment<'static>,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let app = Router::new().route("/", get(|| async { Html("<h1>Hello, World! 2</h1>") }));
|
||||
let mut tmpl_env = Environment::new();
|
||||
tmpl_env
|
||||
.add_template("base", include_str!("../templates/base.html"))
|
||||
.unwrap();
|
||||
|
||||
let app_state = Arc::new(AppState { tmpl_env });
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", get(handler_home))
|
||||
.with_state(app_state);
|
||||
|
||||
// Add hot reload only on dev mode
|
||||
#[cfg(debug_assertions)]
|
||||
|
|
@ -13,3 +31,11 @@ async fn main() {
|
|||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
async fn handler_home(State(state): State<Arc<AppState>>) -> Result<Html<String>, StatusCode> {
|
||||
let template = state.tmpl_env.get_template("base").unwrap();
|
||||
|
||||
let content = template.render(context!()).unwrap();
|
||||
|
||||
Ok(Html(content))
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue