Skip to main content

minijinja_lua/
lib.rs

1// SPDX-License-Identifier: MIT
2
3pub mod contrib;
4mod convert;
5mod environment;
6mod state;
7
8use mlua::LuaSerdeExt;
9
10pub use crate::{
11    environment::LuaEnvironment,
12    state::{LuaStateMut, LuaStateRef},
13};
14
15/// Builds and returns the `minijinja` lua table.
16///
17/// The returned table has the following keys:
18///
19/// - [`Environment`](LuaEnvironment): `userdata` provides access to a [`minijinja::Environment`]
20/// - [`None`](mlua::Value::NULL): a nil-like `lightuserdata` that can be used without the downsides
21///   of `nil`. It maps to [`minijinja::value::ValueKind::None`]
22/// - `path_loader()`: creates a callback function which can be passed to `Environment:set_loader()`
23///   to load templates from the filesystem.
24/// - `type()`: a function to return types for minijinja-lua objects.
25#[cfg_attr(feature = "module", mlua::lua_module(name = "minijinja"))]
26pub fn minijinja_lua(lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
27    let table = lua.create_table()?;
28
29    table.set(
30        "type",
31        lua.create_function(|_, val: mlua::Value| contrib::minijinja_types(&val))?,
32    )?;
33
34    let path_loader = contrib::minijinja_path_loader(lua)?;
35    table.set(
36        "path_loader",
37        lua.create_function(move |_, val: mlua::Value| -> Result<mlua::Function, _> {
38            path_loader.call(val)
39        })?,
40    )?;
41
42    table.set("None", lua.null())?;
43    table.set("Environment", lua.create_proxy::<LuaEnvironment>()?)?;
44
45    Ok(table)
46}