2024-11-08 22:38:54 +00:00
|
|
|
use axum::{http::StatusCode, response::{Html, IntoResponse}};
|
|
|
|
use fully_pub::fully_pub;
|
|
|
|
use log::error;
|
|
|
|
use minijinja::{context, Environment, Value};
|
|
|
|
|
2024-11-11 13:49:17 +00:00
|
|
|
use crate::models::token_claims::UserTokenClaims;
|
2024-11-08 22:38:54 +00:00
|
|
|
|
|
|
|
|
2024-11-16 13:30:01 +00:00
|
|
|
#[derive(Debug, Clone)]
|
2024-11-08 22:38:54 +00:00
|
|
|
#[fully_pub]
|
|
|
|
struct TemplateRenderer {
|
|
|
|
env: Environment<'static>,
|
2024-11-11 13:49:17 +00:00
|
|
|
token_claims: Option<UserTokenClaims>
|
2024-11-08 22:38:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2024-11-08 22:38:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|