use parking_lot::RwLock;
use std::sync::Arc;
use wordval_core::Result;
#[derive(Clone)]
pub struct TemplateEngine {
tera: Arc<RwLock<tera::Tera>>,
}
impl TemplateEngine {
pub fn new() -> Self {
Self {
tera: Arc::new(RwLock::new(tera::Tera::default())),
}
}
pub fn from_dir(dir: &str) -> Result<Self> {
let glob = format!("{}/**/*", dir.trim_end_matches('/'));
let tera = tera::Tera::new(&glob)
.map_err(|e| wordval_core::Error::Template(format!("模板加载失败 {}: {}", dir, e)))?;
Ok(Self {
tera: Arc::new(RwLock::new(tera)),
})
}
pub fn render<C: serde::Serialize>(&self, name: &str, ctx: &C) -> Result<String> {
let ctx = tera::Context::from_serialize(ctx)
.map_err(|e| wordval_core::Error::Template(format!("模板上下文序列化失败: {}", e)))?;
self.tera
.read()
.render(name, &ctx)
.map_err(|e| wordval_core::Error::Template(format!("模板渲染失败: {}", e)))
}
pub fn render_str<C: serde::Serialize>(&self, source: &str, ctx: &C) -> Result<String> {
let ctx = tera::Context::from_serialize(ctx)
.map_err(|e| wordval_core::Error::Template(format!("模板上下文序列化失败: {}", e)))?;
let mut t = tera::Tera::default();
t.add_raw_template("__tpl__", source)
.map_err(|e| wordval_core::Error::Template(format!("模板编译失败: {}", e)))?;
t.render("__tpl__", &ctx)
.map_err(|e| wordval_core::Error::Template(format!("模板渲染失败: {}", e)))
}
}
impl Default for TemplateEngine {
fn default() -> Self {
Self::new()
}
}