-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathtemplate.rs
More file actions
72 lines (60 loc) · 2.03 KB
/
template.rs
File metadata and controls
72 lines (60 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use minijinja::Environment;
use std::sync::RwLock;
/// Template engine for AIScript
pub struct TemplateEngine {
env: RwLock<Environment<'static>>,
}
impl TemplateEngine {
/// Create a new template engine
pub fn new() -> Self {
let mut env = Environment::new();
//Set the source to the templates directory
env.set_loader(|name| -> Result<Option<String>, minijinja::Error> {
let path = std::path::Path::new("templates").join(name);
match std::fs::read_to_string(path) {
Ok(content) => Ok(Some(content)),
Err(_) => Ok(None),
}
});
Self {
env: RwLock::new(env),
}
}
/// Render a template with the given context
pub fn render(
&self,
template_name: &str,
context: &serde_json::Value,
) -> Result<String, String> {
let env = self.env.read().unwrap();
// get the template
let template = env
.get_template(template_name)
.map_err(|e| format!("Failed to load template '{}': {}", template_name, e))?;
// render the template and return the result
template
.render(context)
.map_err(|e| format!("Failed to render template '{}': {}", template_name, e))
}
/// Reload the templates
pub fn reload(&self) -> Result<(), String> {
let mut env = self.env.write().unwrap();
//reload templates
env.set_loader(|name| -> Result<Option<String>, minijinja::Error> {
let path = std::path::Path::new("templates").join(name);
match std::fs::read_to_string(path) {
Ok(content) => Ok(Some(content)),
Err(_) => Ok(None),
}
});
Ok(())
}
}
//Create a global instance of the template engine
lazy_static::lazy_static! {
static ref TEMPLATE_ENGINE: TemplateEngine = TemplateEngine::new();
}
//Get the template engine instance
pub fn get_template_engine() -> &'static TemplateEngine {
&TEMPLATE_ENGINE
}