2023-10-22 17:43:30 -04:00
use std ::collections ::HashMap ;
2023-10-22 17:37:27 -04:00
use crate ::error ::CustomError ;
2023-10-22 16:26:43 -04:00
use super ::renderer_integration ::RendererIntegration ;
2023-10-22 16:40:58 -04:00
use serde ::Serialize ;
2023-10-22 16:26:43 -04:00
2023-10-22 17:43:30 -04:00
pub ( crate ) struct DusterRenderer < ' a > {
templates : HashMap < & ' a str , duster ::parser ::Template < ' a > > ,
}
2023-10-22 16:26:43 -04:00
2023-10-22 17:43:30 -04:00
impl < ' a > DusterRenderer < ' a > {
pub ( crate ) fn new ( ) -> DusterRenderer < ' a > {
DusterRenderer {
templates : HashMap ::new ( ) ,
}
2023-10-22 17:31:12 -04:00
}
}
2023-10-22 17:43:30 -04:00
impl < ' a > RendererIntegration < ' a > for DusterRenderer < ' a > {
fn load_template ( & mut self , name : & ' a str , contents : & ' a str ) -> Result < ( ) , CustomError > {
2023-10-22 17:37:27 -04:00
let compiled_template = duster ::renderer ::compile_template ( contents . as_ref ( ) ) ? ;
2023-10-22 17:43:30 -04:00
self . templates . insert ( name , compiled_template ) ;
2023-10-22 16:40:58 -04:00
Ok ( ( ) )
2023-10-22 16:26:43 -04:00
}
2023-10-22 17:37:27 -04:00
fn render < C > ( & self , context : C ) -> Result < String , CustomError >
2023-10-22 16:26:43 -04:00
where
2023-10-22 16:40:58 -04:00
C : Serialize ,
2023-10-22 16:26:43 -04:00
{
2023-10-22 18:30:01 -04:00
let mut dust_renderer = duster ::renderer ::DustRenderer ::new ( ) ;
for ( name , compiled_template ) in self . templates . iter ( ) {
dust_renderer . load_source ( compiled_template , ( * name ) . to_owned ( ) ) ;
}
// TODO: This is horribly inefficient. I am converting from a serialize type to json and back again so I can use the existing implementation of IntoContextElement. Honestly, I probably need to rework a lot of duster now that I've improved in rust over the years.
let json_context = serde_json ::to_string ( & context ) ? ;
println! ( " Context: {} " , json_context ) ;
let parsed_context : serde_json ::Value = serde_json ::from_str ( json_context . as_str ( ) ) ? ;
let rendered_output = dust_renderer . render ( " main " , Some ( & parsed_context ) ) ? ;
Ok ( rendered_output )
2023-10-22 16:26:43 -04:00
}
}