docx_handlebars/
lib.rs

1use wasm_bindgen::prelude::*;
2use wasm_bindgen::JsValue;
3
4pub mod errors;
5pub mod ole;
6pub mod template;
7pub mod utils;
8
9// 重新导出常用的类型和函数
10pub use errors::DocxError;
11pub use template::render_handlebars;
12
13/// 当 `console_error_panic_hook` 功能启用时,我们可以调用 `set_panic_hook` 函数
14/// 至少一次在初始化过程中,以便在 panic 时获得更好的错误消息。
15pub fn set_panic_hook() {
16    #[cfg(feature = "console_error_panic_hook")]
17    console_error_panic_hook::set_once();
18}
19
20/// 主要的 DOCX Handlebars 处理器
21#[wasm_bindgen]
22pub fn render(
23    zip_bytes: Vec<u8>,
24    data_json: &str,
25) -> Result<JsValue, JsValue> {
26    let data: serde_json::Value = serde_json::from_str(data_json)
27            .map_err(|e| JsValue::from_str(&format!("JSON 解析错误: {e}")))?;
28
29    // 调用模板渲染函数
30    let result = template::render_handlebars(zip_bytes, &data)
31        .map_err(|e| JsValue::from_str(&e.to_string()))?;
32
33    // 返回结果
34    Ok(JsValue::from(result))
35}