minauthator/src/renderer.rs

46 lines
1.3 KiB
Rust
Raw Normal View History

use axum::{http::StatusCode, response::{Html, IntoResponse}};
use fully_pub::fully_pub;
use log::error;
use minijinja::{context, Environment, Value};
use crate::models::token_claims::UserTokenClaims;
#[derive(Clone)]
#[fully_pub]
struct TemplateRenderer {
env: Environment<'static>,
token_claims: Option<UserTokenClaims>
}
impl TemplateRenderer {
/// Helper method to output HTML as response
pub(crate) fn render(&self, name: &str, ctx: Value) -> impl IntoResponse {
match self
.env
.get_template(&format!("{name}.html"))
.and_then(|tmpl| tmpl.render(context! {
token_claims => self.token_claims,
..ctx
}))
{
Ok(content) => Html(content).into_response(),
Err(err) => {
dbg!(err);
error!("FATAL: Failed to render template {}", name);
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error").into_response()
}
}
}
pub(crate) fn render_with_status(&self, status: StatusCode, name: &str, ctx: Value) -> impl IntoResponse {
let mut res = self.render(name, ctx).into_response();
if res.status().is_server_error() {
return res
}
*res.status_mut() = status;
2024-11-12 13:29:27 +00:00
res
}
}