natter/src/render/duster_renderer.rs

43 lines
1.6 KiB
Rust
Raw Normal View History

use std::collections::HashMap;
use crate::error::CustomError;
use super::renderer_integration::RendererIntegration;
2023-10-22 16:40:58 -04:00
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);
2023-10-22 16:40:58 -04:00
Ok(())
}
fn render<C>(&self, context: C) -> Result<String, CustomError>
where
2023-10-22 16:40:58 -04:00
C: Serialize,
{
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)
}
}