1- use minijinja:: { Environment , Source } ;
1+ use minijinja:: Environment ;
22use std:: path:: Path ;
33use std:: sync:: Arc ;
44use std:: sync:: RwLock ;
@@ -15,32 +15,44 @@ impl TemplateEngine {
1515 let mut env = Environment :: new ( ) ;
1616
1717 //Set the source to the templates directory
18- let source = Source :: from_path ( "templates" ) ;
19- env. set_source ( source) ;
18+ env. set_loader ( |name| -> Result < Option < String > , minijinja:: Error > {
19+ let path = std:: path:: Path :: new ( "templates" ) . join ( name) ;
20+ match std:: fs:: read_to_string ( path) {
21+ Ok ( content) => Ok ( Some ( content) ) ,
22+ Err ( _) => Ok ( None )
23+ }
24+ } ) ;
2025
2126 Self {
2227 env : RwLock :: new ( env) ,
2328 }
2429 }
2530
2631 /// Render a template with the given context
27- pub fn render ( & self , template_name : & str , context : serde_json:: Value ) -> Result < String , String > {
32+ pub fn render ( & self , template_name : & str , context : & serde_json:: Value ) -> Result < String , String > {
2833 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) ) ?;
34+
35+ // 获取模板
36+ let template = env. get_template ( template_name)
37+ . map_err ( |e| format ! ( "Failed to load template '{}': {}" , template_name, e) ) ?;
38+
39+ // 渲染模板并返回结果
40+ template. render ( context)
41+ . map_err ( |e| format ! ( "Failed to render template '{}': {}" , template_name, e) )
3542 }
3643
3744 /// Reload the templates
3845 pub fn reload ( & self ) -> Result < ( ) , String > {
3946 let mut env = self . env . write ( ) . unwrap ( ) ;
4047
4148 //reload templates
42- let source = Source :: from_path ( "templates" ) ;
43- env. set_source ( source) ;
49+ env. set_loader ( |name| -> Result < Option < String > , minijinja:: Error > {
50+ let path = std:: path:: Path :: new ( "templates" ) . join ( name) ;
51+ match std:: fs:: read_to_string ( path) {
52+ Ok ( content) => Ok ( Some ( content) ) ,
53+ Err ( _) => Ok ( None )
54+ }
55+ } ) ;
4456
4557 Ok ( ( ) )
4658 }
0 commit comments