3 releases

0.1.2 Sep 18, 2023
0.1.1 Aug 29, 2023
0.1.0 Aug 11, 2023

#273 in Template engine

Download history 47/week @ 2024-03-25 30/week @ 2024-04-01 50/week @ 2024-04-08 45/week @ 2024-04-15 12/week @ 2024-04-22 2/week @ 2024-04-29 24/week @ 2024-05-06 28/week @ 2024-05-13 16/week @ 2024-05-20 8/week @ 2024-06-03 14/week @ 2024-06-10 10/week @ 2024-06-17 12/week @ 2024-06-24 54/week @ 2024-07-01 24/week @ 2024-07-08

101 downloads per month

MIT license

14KB
321 lines

rhai-tpl

Customizable template engine that uses rhai for its logic.

Templating

Use <% %> for running logic you don't want to write to the template and use <%= %> for writing.

<%
let a = [42, 123, 999, 0, true, "hello", "world!", 987.6543];

// Loop through the array
for (item, count) in a { %>
Item #<%= count + 1 %> = <%= item %>
<% } %>

Returns:

Item #1 = 42
Item #2 = 123
Item #3 = 999
Item #4 = 0
Item #5 = true
Item #6 = hello
Item #7 = world!
Item #8 = 987.6543

Rendering

The rhai_tpl::Engine enables rendering and customization. It has 2 generic params: W: Write and S: State which is state you can use when modifying the engine. it is implemented by default for any type implementing Clone + Send + Sync + 'static.

let f = std::fs::OpenOptions::new()
    .create(true)
    .write(true)
    .open(&filepath)?;

let engine = rhai_tpl::Engine::new::<std::fs::File, ()>();

let input = ""; // you'd fetch this from a file or whatever

let tpl = engine.compile(input)?;

tpl.render(f, ())?;

Customizing

You can mutate the engine directly by adding / modifying functions available to users:

let mut engine = Engine::new::<std::fs::File, ()>();

engine.register_fn(
    "write",
    |tw: &mut TemplateWriter<std::fs::File, ()>,
        d: Dynamic|
        -> Result<(), Box<EvalAltResult>> {
        tw.write_all(format!("overloaded: {d}").as_bytes())
            .map_err(|e| Box::new(EvalAltResult::from(e.to_string())))?;
        Ok(())
    },
);

This modification overrides the default write output for the rhai::Dynamic type and prefixes it with overloaded: . It's not particularly useful, but it gives you an idea.

Dependencies

~6–12MB
~97K SLoC