@@ -3,7 +3,6 @@ use std::path::Path;
3
3
use std:: sync:: Arc ;
4
4
use std:: sync:: RwLock ;
5
5
6
-
7
6
/// Template engine for AIScript
8
7
pub struct TemplateEngine {
9
8
env : RwLock < Environment < ' static > > ,
@@ -19,7 +18,7 @@ impl TemplateEngine {
19
18
let path = std:: path:: Path :: new ( "templates" ) . join ( name) ;
20
19
match std:: fs:: read_to_string ( path) {
21
20
Ok ( content) => Ok ( Some ( content) ) ,
22
- Err ( _) => Ok ( None )
21
+ Err ( _) => Ok ( None ) ,
23
22
}
24
23
} ) ;
25
24
@@ -29,41 +28,47 @@ impl TemplateEngine {
29
28
}
30
29
31
30
/// Render a template with the given context
32
- pub fn render ( & self , template_name : & str , context : & serde_json:: Value ) -> Result < String , String > {
31
+ pub fn render (
32
+ & self ,
33
+ template_name : & str ,
34
+ context : & serde_json:: Value ,
35
+ ) -> Result < String , String > {
33
36
let env = self . env . read ( ) . unwrap ( ) ;
34
-
35
- // 获取模板
36
- let template = env. get_template ( template_name)
37
+
38
+ // get the template
39
+ let template = env
40
+ . get_template ( template_name)
37
41
. map_err ( |e| format ! ( "Failed to load template '{}': {}" , template_name, e) ) ?;
38
-
39
- // 渲染模板并返回结果
40
- template. render ( context)
42
+
43
+ // render the template and return the result
44
+ template
45
+ . render ( context)
41
46
. map_err ( |e| format ! ( "Failed to render template '{}': {}" , template_name, e) )
42
47
}
43
48
44
49
/// Reload the templates
45
50
pub fn reload ( & self ) -> Result < ( ) , String > {
46
- let mut env = self . env . write ( ) . unwrap ( ) ;
51
+ let mut env = self . env . write ( ) . unwrap ( ) ;
47
52
48
- //reload templates
53
+ //reload templates
49
54
env. set_loader ( |name| -> Result < Option < String > , minijinja:: Error > {
50
55
let path = std:: path:: Path :: new ( "templates" ) . join ( name) ;
51
56
match std:: fs:: read_to_string ( path) {
52
57
Ok ( content) => Ok ( Some ( content) ) ,
53
- Err ( _) => Ok ( None )
58
+ Err ( _) => Ok ( None ) ,
54
59
}
55
60
} ) ;
56
61
57
62
Ok ( ( ) )
58
63
}
59
64
}
60
65
61
- //Create a global instance of the template engine
66
+ //Create a global instance of the template engine
62
67
lazy_static:: lazy_static! {
63
68
static ref TEMPLATE_ENGINE : TemplateEngine = TemplateEngine :: new( ) ;
64
69
}
65
70
66
- //Get the template engine instance
71
+ //Get the template engine instance
67
72
pub fn get_template_engine ( ) -> & ' static TemplateEngine {
68
73
& TEMPLATE_ENGINE
69
- }
74
+ }
0 commit comments