use crate::Result;
use crate::runtime::Runtime;
use mlua::{Lua, Table, Value};
pub fn init_module(lua: &Lua, _runtime: &Runtime) -> Result<Table> {
let table = lua.create_table()?;
table.set("render", lua.create_function(render)?)?;
Ok(table)
}
fn render(_lua: &Lua, (content, data): (String, Value)) -> mlua::Result<String> {
let data_serde = serde_json::to_value(&data)
.map_err(|err| crate::Error::custom(format!("Fail to convert lua value to serde. Cause: {err}")))?;
let rendered = crate::support::hbs::hbs_render(&content, &data_serde).map_err(mlua::Error::external)?;
Ok(rendered)
}
#[cfg(test)]
mod tests {
type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;
use crate::_test_support::{assert_contains, eval_lua, setup_lua};
use crate::script::lua_script::aip_hbs;
#[tokio::test]
async fn test_lua_hbs_render_simple() -> Result<()> {
let lua = setup_lua(aip_hbs::init_module, "hbs")?;
let lua_code = r#"
local result = aip.hbs.render("Hello, {{name}}!", {name = "World"})
return result
"#;
let res = eval_lua(&lua, lua_code)?;
assert_eq!(res.as_str().ok_or("Result should be a string")?, "Hello, World!");
Ok(())
}
#[tokio::test]
async fn test_lua_hbs_render_obj() -> Result<()> {
let lua = setup_lua(aip_hbs::init_module, "hbs")?;
let lua_code = r#"
local result = aip.hbs.render("ID: {{id}}, Nested: {{nested.value}}", {id = 42, nested = {value = "test"}})
return result
"#;
let res = eval_lua(&lua, lua_code)?;
assert_eq!(res.as_str().ok_or("Result should be a string")?, "ID: 42, Nested: test");
Ok(())
}
#[tokio::test]
async fn test_lua_hbs_render_list() -> Result<()> {
let lua = setup_lua(aip_hbs::init_module, "hbs")?;
let lua_code = r#"
local data = {
name = "Jen Donavan",
todos = {"Bug Triage AIPACK", "Fix Windows Support"}
}
local template = [[
Hello {{name}},
Your tasks today:
{{#each todos}}
- {{this}}
{{/each}}
Have a good day (after you completed this tasks)
]]
local content = aip.hbs.render(template, data)
return content
"#;
let res = eval_lua(&lua, lua_code)?;
let content = res.as_str().ok_or("Should have returned a string")?;
assert_contains(content, "Hello Jen Donavan");
assert_contains(content, "- Bug Triage AIPACK");
assert_contains(content, "- Fix Windows Support");
Ok(())
}
}