43 lines
1.6 KiB
Rust
43 lines
1.6 KiB
Rust
use std::collections::HashMap;
|
|
|
|
use crate::error::CustomError;
|
|
|
|
use super::renderer_integration::RendererIntegration;
|
|
use serde::Serialize;
|
|
|
|
pub(crate) struct DusterRenderer<'a> {
|
|
templates: HashMap<&'a str, duster::parser::Template<'a>>,
|
|
}
|
|
|
|
impl<'a> DusterRenderer<'a> {
|
|
pub(crate) fn new() -> DusterRenderer<'a> {
|
|
DusterRenderer {
|
|
templates: HashMap::new(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'a> RendererIntegration<'a> for DusterRenderer<'a> {
|
|
fn load_template(&mut self, name: &'a str, contents: &'a str) -> Result<(), CustomError> {
|
|
let compiled_template = duster::renderer::compile_template(contents.as_ref())?;
|
|
self.templates.insert(name, compiled_template);
|
|
Ok(())
|
|
}
|
|
|
|
fn render<C>(&self, context: C) -> Result<String, CustomError>
|
|
where
|
|
C: Serialize,
|
|
{
|
|
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)
|
|
}
|
|
}
|