Skip to content

Commit ab33589

Browse files
committed
set template and render
1 parent 7cf7854 commit ab33589

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

aiscript-runtime/src/template.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
use minijinja::{Environment, Source};
2+
use std::path::Path;
3+
use std::sync::Arc;
4+
use std::sync::RwLock;
5+
6+
7+
/// Template engine for AIScript
8+
pub struct TemplateEngine {
9+
env: RwLock<Environment<'static>>,
10+
}
11+
12+
impl TemplateEngine {
13+
/// Create a new template engine
14+
pub fn new() -> Self {
15+
let mut env = Environment::new();
16+
17+
//Set the source to the templates directory
18+
let source = Source::from_path("templates");
19+
env.set_source(source);
20+
21+
Self {
22+
env: RwLock::new(env),
23+
}
24+
}
25+
26+
/// Render a template with the given context
27+
pub fn render(&self, template_name: &str, context: serde_json::Value) -> Result<String, String> {
28+
let env = self.env.read().unwrap();
29+
30+
//get template
31+
let template = env.get_template(template_name).map_err(|e| format!("Failed to get template: {}", e))?;
32+
33+
//render template
34+
let rendered = template.render(&context).map_err(|e| format!("Failed to render template: {}", e))?;
35+
}
36+
37+
/// Reload the templates
38+
pub fn reload(&self) -> Result<(), String> {
39+
let mut env = self.env.write().unwrap();
40+
41+
//reload templates
42+
let source = Source::from_path("templates");
43+
env.set_source(source);
44+
45+
Ok(())
46+
}
47+
}
48+
49+
//Create a global instance of the template engine
50+
lazy_static::lazy_static! {
51+
static ref TEMPLATE_ENGINE: TemplateEngine = TemplateEngine::new();
52+
}
53+
54+
//Get the template engine instance
55+
pub fn get_template_engine() -> &'static TemplateEngine {
56+
&TEMPLATE_ENGINE
57+
}

aiscript-vm/src/stdlib/web.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
use crate::value::Value;
2+
use aiscript_runtime::template::get_template_engine;
3+
4+
/// Render a template with the given context
5+
pub fn render(args: &[Value]) -> Result<Value, String> {
6+
if args.len() != 2 {
7+
return Err("render expects 2 arguments: template name and context".to_string());
8+
}
9+
10+
//get the template name
11+
let template_name = args[0].as_str().ok_or_else(|| "First argument must be a string (template name)".to_string())?;
12+
13+
//get the context
14+
let context = serde_json::to_value(&args[1])
15+
.map_err(|e| format!("Failed to convert context to JSON: {}", e))?;
16+
17+
//render the template
18+
let result = get_template_engine().render(template_name, context)?;
19+
20+
OK(Value::String(result.into()))
21+
22+
}

0 commit comments

Comments
 (0)