reorganize module

This commit is contained in:
Timur Gordon
2025-04-04 08:28:07 +02:00
parent 1ea37e2e7f
commit 939b6b4e57
375 changed files with 7580 additions and 191 deletions

1119
rhai_tera/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

10
rhai_tera/Cargo.toml Normal file
View File

@@ -0,0 +1,10 @@
[package]
name = "rhai_tera"
version = "0.1.0"
edition = "2021"
description = "Integration between Rhai scripting and Tera templating"
[dependencies]
rhai = { version = "1.15.1", features = ["serde"] }
tera = "1.19.0"
serde_json = "1.0.107"

65
rhai_tera/src/lib.rs Normal file
View File

@@ -0,0 +1,65 @@
use rhai::{Engine, Scope, Dynamic};
use std::collections::HashMap;
use tera::{Function as TeraFunction, Value, Result as TeraResult};
use tera::Tera;
use std::path::PathBuf;
use serde_json;
pub struct RhaiFunctionAdapter {
fn_name: String,
script_path: PathBuf,
}
impl TeraFunction for RhaiFunctionAdapter {
fn call(&self, args: &HashMap<String, Value>) -> TeraResult<Value> {
let mut scope = Scope::new();
// Convert args from Tera into Rhai's Dynamic
for (key, value) in args {
let json_str = serde_json::to_string(value).unwrap();
let json_value: serde_json::Value = serde_json::from_str(&json_str).unwrap();
let dynamic = rhai::serde::to_dynamic(json_value).unwrap();
scope.push_dynamic(key.clone(), dynamic);
}
// Build engine and compile AST inside call (safe)
let engine = Engine::new();
let ast = engine
.compile_file(self.script_path.clone())
.map_err(|e| tera::Error::msg(format!("Rhai compile error: {}", e)))?;
let result = engine
.call_fn::<Dynamic>(&mut scope, &ast, &self.fn_name, ())
.map_err(|e| tera::Error::msg(format!("Rhai error: {}", e)))?;
let tera_value = rhai::serde::from_dynamic(&result).unwrap();
Ok(tera_value)
}
}
/// Sets up a Tera instance with a Rhai function adapter
///
/// # Arguments
/// * `templates_path` - Path to the templates directory
/// * `fn_name` - Name of the Rhai function to call
/// * `script_path` - Path to the Rhai script file
/// * `tera_fn_name` - Name to register the function as in Tera
///
/// # Returns
/// A configured Tera instance with the Rhai function registered
pub fn setup_tera_with_rhai(
templates_path: &str,
fn_name: &str,
script_path: PathBuf,
tera_fn_name: &str
) -> Tera {
let mut tera = Tera::new(templates_path).unwrap();
let adapter = RhaiFunctionAdapter {
fn_name: fn_name.into(),
script_path,
};
tera.register_function(tera_fn_name, adapter);
tera
}