use axum::{http::StatusCode, response::{Html, IntoResponse}}; use fully_pub::fully_pub; use kernel::models::config::Config; use log::error; use minijinja::{context, Environment, Value}; use utils::encode_base64_picture; use crate::token_claims::UserTokenClaims; #[derive(Debug, Clone)] #[fully_pub] struct TemplateRenderer { env: Environment<'static>, token_claims: Option } 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; res } } pub fn build_templating_env(config: &Config) -> Environment<'static> { let mut env = Environment::new(); minijinja_embed::load_templates!(&mut env); env.add_global("gl", context! { instance => config.instance }); env.add_function("inline_picture", encode_base64_picture); env }