minijinja running

This commit is contained in:
Per Stark
2024-12-18 20:37:31 +01:00
parent 7712537f23
commit e54533d005
10 changed files with 1402 additions and 31 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,6 @@ use minijinja::{path_loader, Environment};
use minijinja_autoreload::AutoReloader;
use std::{path::PathBuf, sync::Arc};
use surrealdb::{engine::any::Any, Surreal};
use tera::Tera;
use tower_http::services::ServeDir;
use tracing::info;
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
@@ -64,7 +63,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
rabbitmq_producer: Arc::new(RabbitMQProducer::new(&config).await?),
rabbitmq_consumer: Arc::new(RabbitMQConsumer::new(&config, false).await?),
surreal_db_client: Arc::new(SurrealDbClient::new().await?),
// tera: Arc::new(Tera::new("templates/**/*.html").unwrap()),
openai_client: Arc::new(async_openai::Client::new()),
templates: Arc::new(reloader),
};

View File

@@ -68,6 +68,8 @@ pub enum ApiError {
UserNotFound,
#[error("You must provide valid credentials")]
AuthRequired,
#[error("Templating error: {0}")]
TemplatingError(#[from] minijinja::Error),
}
impl IntoResponse for ApiError {
@@ -87,6 +89,7 @@ impl IntoResponse for ApiError {
}
ApiError::RabbitMQError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
ApiError::FileError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
ApiError::TemplatingError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
};
(

View File

@@ -3,7 +3,6 @@ use crate::rabbitmq::publisher::RabbitMQProducer;
use crate::storage::db::SurrealDbClient;
use minijinja_autoreload::AutoReloader;
use std::sync::Arc;
// use tera::Tera;
pub mod middleware_api_auth;
pub mod routes;
@@ -13,7 +12,6 @@ pub struct AppState {
pub rabbitmq_producer: Arc<RabbitMQProducer>,
pub rabbitmq_consumer: Arc<RabbitMQConsumer>,
pub surreal_db_client: Arc<SurrealDbClient>,
// pub tera: Arc<Tera>,
pub openai_client: Arc<async_openai::Client<async_openai::config::OpenAIConfig>>,
pub templates: Arc<AutoReloader>,
}

View File

@@ -1,5 +1,6 @@
use axum::{
extract::State,
http::Response,
response::{Html, IntoResponse},
Form,
};
@@ -11,23 +12,34 @@ use surrealdb::{engine::any::Any, Surreal};
use crate::{error::ApiError, server::AppState, storage::types::user::User};
use super::{render_block, render_template};
#[derive(Deserialize, Serialize)]
pub struct SignupParams {
pub email: String,
pub password: String,
}
#[derive(Serialize)]
struct PageData {
// name: String,
}
pub async fn show_signup_form(
State(state): State<AppState>,
HxBoosted(boosted): HxBoosted,
) -> Html<String> {
let mut context = tera::Context::new();
context.insert("boosted", &boosted);
// let html = state
// .tera
// .render("auth/signup_form.html", &context)
// .unwrap_or_else(|_| "<h1>Error rendering template</h1>".to_string());
Html("html".to_string())
) -> Result<Html<String>, ApiError> {
let output = match boosted {
true => render_block(
"auth/signup_form.html",
"content",
PageData {},
state.templates,
)?,
false => render_template("auth/signup_form.html", PageData {}, state.templates)?,
};
Ok(output)
}
pub async fn signup_handler(

View File

@@ -2,13 +2,23 @@ use axum::{extract::State, response::Html};
use axum_session_auth::AuthSession;
use axum_session_surreal::SessionSurrealPool;
use minijinja::context;
use serde::Serialize;
use serde_json::json;
use surrealdb::{engine::any::Any, sql::Relation, Surreal};
use tera::Context;
// use tera::Context;
use tracing::info;
use crate::{error::ApiError, server::AppState, storage::types::user::User};
use crate::{
error::ApiError,
server::{routes::render_template, AppState},
storage::types::user::User,
};
#[derive(Serialize)]
struct PageData<'a> {
queue_length: &'a str,
}
pub async fn index_handler(
State(state): State<AppState>,
@@ -20,21 +30,13 @@ pub async fn index_handler(
let queue_length = state.rabbitmq_consumer.get_queue_length().await?;
// let output = state
// .tera
// .render(
// "index.html",
// &Context::from_value(json!({"adjective": "CRAYCRAY", "queue_length": queue_length}))
// .unwrap(),
// )
// .unwrap();
let output = render_template(
"index.html",
PageData {
queue_length: "1000",
},
state.templates,
)?;
// Ok(output.into())
//
let env = state.templates.acquire_env().unwrap();
let context = context!(queue_length => "2000");
let tmpl = env.get_template("index.html").unwrap();
let output = tmpl.render(context).unwrap();
Ok(output.into())
Ok(output)
}

View File

@@ -1,3 +1,8 @@
use std::sync::Arc;
use axum::response::Html;
use minijinja_autoreload::AutoReloader;
pub mod auth;
pub mod file;
pub mod index;
@@ -5,3 +10,38 @@ pub mod ingress;
pub mod query;
pub mod queue_length;
pub mod search_result;
pub fn render_template<T>(
template_name: &str,
context: T,
templates: Arc<AutoReloader>,
) -> Result<Html<String>, minijinja::Error>
where
T: serde::Serialize,
{
let env = templates.acquire_env()?;
let tmpl = env.get_template(template_name)?;
let context = minijinja::Value::from_serialize(&context);
let output = tmpl.render(context)?;
Ok(output.into())
}
pub fn render_block<T>(
template_name: &str,
block: &str,
context: T,
templates: Arc<AutoReloader>,
) -> Result<Html<String>, minijinja::Error>
where
T: serde::Serialize,
{
let env = templates.acquire_env()?;
let tmpl = env.get_template(template_name)?;
let context = minijinja::Value::from_serialize(&context);
let output = tmpl.eval_to_state(context)?.render_block(block)?;
Ok(output.into())
}

View File

@@ -1,7 +1,7 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./src/server/templates/**/*'
'./templates/**/*'
],
theme: {
extend: {},

View File

@@ -1,3 +1,4 @@
HELLO THIS IS OUTSIDE THE BLOCK
{% block content %}
<div class="max-h-full grid place-items-center place-content-center">
<div class="max-w-md mx-auto">

View File

@@ -1,3 +1,5 @@
{% extends "body_base.html" %}
{% block content %}
<div class="flex flex-col items-center justify-center min-h-[80vh] space-y-8">
<!-- Hero Section -->
<div class="text-center space-y-4 mb-8">
@@ -24,4 +26,5 @@
<div id="search-results" class="w-full max-w-2xl mt-4">
<!-- Results will be populated here by HTMX -->
</div>
</div>
</div>
{% endblock %}