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+ }
0 commit comments