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 minijinja_autoreload::AutoReloader;
use std::{path::PathBuf, sync::Arc}; use std::{path::PathBuf, sync::Arc};
use surrealdb::{engine::any::Any, Surreal}; use surrealdb::{engine::any::Any, Surreal};
use tera::Tera;
use tower_http::services::ServeDir; use tower_http::services::ServeDir;
use tracing::info; use tracing::info;
use tracing_subscriber::{fmt, prelude::*, EnvFilter}; 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_producer: Arc::new(RabbitMQProducer::new(&config).await?),
rabbitmq_consumer: Arc::new(RabbitMQConsumer::new(&config, false).await?), rabbitmq_consumer: Arc::new(RabbitMQConsumer::new(&config, false).await?),
surreal_db_client: Arc::new(SurrealDbClient::new().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()), openai_client: Arc::new(async_openai::Client::new()),
templates: Arc::new(reloader), templates: Arc::new(reloader),
}; };

View File

@@ -68,6 +68,8 @@ pub enum ApiError {
UserNotFound, UserNotFound,
#[error("You must provide valid credentials")] #[error("You must provide valid credentials")]
AuthRequired, AuthRequired,
#[error("Templating error: {0}")]
TemplatingError(#[from] minijinja::Error),
} }
impl IntoResponse for ApiError { impl IntoResponse for ApiError {
@@ -87,6 +89,7 @@ impl IntoResponse for ApiError {
} }
ApiError::RabbitMQError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()), ApiError::RabbitMQError(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
ApiError::FileError(_) => (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 crate::storage::db::SurrealDbClient;
use minijinja_autoreload::AutoReloader; use minijinja_autoreload::AutoReloader;
use std::sync::Arc; use std::sync::Arc;
// use tera::Tera;
pub mod middleware_api_auth; pub mod middleware_api_auth;
pub mod routes; pub mod routes;
@@ -13,7 +12,6 @@ pub struct AppState {
pub rabbitmq_producer: Arc<RabbitMQProducer>, pub rabbitmq_producer: Arc<RabbitMQProducer>,
pub rabbitmq_consumer: Arc<RabbitMQConsumer>, pub rabbitmq_consumer: Arc<RabbitMQConsumer>,
pub surreal_db_client: Arc<SurrealDbClient>, pub surreal_db_client: Arc<SurrealDbClient>,
// pub tera: Arc<Tera>,
pub openai_client: Arc<async_openai::Client<async_openai::config::OpenAIConfig>>, pub openai_client: Arc<async_openai::Client<async_openai::config::OpenAIConfig>>,
pub templates: Arc<AutoReloader>, pub templates: Arc<AutoReloader>,
} }

View File

@@ -1,5 +1,6 @@
use axum::{ use axum::{
extract::State, extract::State,
http::Response,
response::{Html, IntoResponse}, response::{Html, IntoResponse},
Form, Form,
}; };
@@ -11,23 +12,34 @@ use surrealdb::{engine::any::Any, Surreal};
use crate::{error::ApiError, server::AppState, storage::types::user::User}; use crate::{error::ApiError, server::AppState, storage::types::user::User};
use super::{render_block, render_template};
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]
pub struct SignupParams { pub struct SignupParams {
pub email: String, pub email: String,
pub password: String, pub password: String,
} }
#[derive(Serialize)]
struct PageData {
// name: String,
}
pub async fn show_signup_form( pub async fn show_signup_form(
State(state): State<AppState>, State(state): State<AppState>,
HxBoosted(boosted): HxBoosted, HxBoosted(boosted): HxBoosted,
) -> Html<String> { ) -> Result<Html<String>, ApiError> {
let mut context = tera::Context::new(); let output = match boosted {
context.insert("boosted", &boosted); true => render_block(
// let html = state "auth/signup_form.html",
// .tera "content",
// .render("auth/signup_form.html", &context) PageData {},
// .unwrap_or_else(|_| "<h1>Error rendering template</h1>".to_string()); state.templates,
Html("html".to_string()) )?,
false => render_template("auth/signup_form.html", PageData {}, state.templates)?,
};
Ok(output)
} }
pub async fn signup_handler( 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_auth::AuthSession;
use axum_session_surreal::SessionSurrealPool; use axum_session_surreal::SessionSurrealPool;
use minijinja::context; use minijinja::context;
use serde::Serialize;
use serde_json::json; use serde_json::json;
use surrealdb::{engine::any::Any, sql::Relation, Surreal}; use surrealdb::{engine::any::Any, sql::Relation, Surreal};
use tera::Context; use tera::Context;
// use tera::Context; // use tera::Context;
use tracing::info; 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( pub async fn index_handler(
State(state): State<AppState>, State(state): State<AppState>,
@@ -20,21 +30,13 @@ pub async fn index_handler(
let queue_length = state.rabbitmq_consumer.get_queue_length().await?; let queue_length = state.rabbitmq_consumer.get_queue_length().await?;
// let output = state let output = render_template(
// .tera "index.html",
// .render( PageData {
// "index.html", queue_length: "1000",
// &Context::from_value(json!({"adjective": "CRAYCRAY", "queue_length": queue_length})) },
// .unwrap(), state.templates,
// ) )?;
// .unwrap();
// Ok(output.into()) Ok(output)
//
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())
} }

View File

@@ -1,3 +1,8 @@
use std::sync::Arc;
use axum::response::Html;
use minijinja_autoreload::AutoReloader;
pub mod auth; pub mod auth;
pub mod file; pub mod file;
pub mod index; pub mod index;
@@ -5,3 +10,38 @@ pub mod ingress;
pub mod query; pub mod query;
pub mod queue_length; pub mod queue_length;
pub mod search_result; 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} */ /** @type {import('tailwindcss').Config} */
module.exports = { module.exports = {
content: [ content: [
'./src/server/templates/**/*' './templates/**/*'
], ],
theme: { theme: {
extend: {}, extend: {},

View File

@@ -1,3 +1,4 @@
HELLO THIS IS OUTSIDE THE BLOCK
{% block content %} {% block content %}
<div class="max-h-full grid place-items-center place-content-center"> <div class="max-h-full grid place-items-center place-content-center">
<div class="max-w-md mx-auto"> <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"> <div class="flex flex-col items-center justify-center min-h-[80vh] space-y-8">
<!-- Hero Section --> <!-- Hero Section -->
<div class="text-center space-y-4 mb-8"> <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"> <div id="search-results" class="w-full max-w-2xl mt-4">
<!-- Results will be populated here by HTMX --> <!-- Results will be populated here by HTMX -->
</div> </div>
</div> </div>
{% endblock %}