#template #templating #traits #formatting #once #data

funcfmt

"Parse once, populate many" templating using function traits

3 releases (breaking)

0.3.0 Apr 25, 2023
0.2.0 Apr 3, 2023
0.1.0 Apr 3, 2023

#270 in Template engine

Download history 19/week @ 2024-07-20 25/week @ 2024-07-27 9/week @ 2024-08-03 6/week @ 2024-08-10 3/week @ 2024-08-17 7/week @ 2024-08-24 14/week @ 2024-08-31 9/week @ 2024-09-07 6/week @ 2024-09-14 32/week @ 2024-09-21 18/week @ 2024-09-28 2/week @ 2024-10-05 7/week @ 2024-10-12 12/week @ 2024-10-19 21/week @ 2024-10-26 16/week @ 2024-11-02

56 downloads per month
Used in 3 crates

MIT license

16KB
245 lines

funcfmt | Tests

funcfmt is a simple, lightweight templating library that allows templating using custom runtime context and function traits. It was originally created for exifrename, to allow efficiently processing a format and set of callbacks across thousands of EXIF objects.

Documentation

Documentation is available on docs.rs, or through cargo doc --open.

Usage

To add funcfmt to your dependencies:

cargo add funcfmt

The basic flow of funcfmt looks like this:

  1. Given a FormatMap<T> called formatters, call formatters.to_format_pieces(), which preprocesses everything into a FormatPieces<T>, where &T is what your callback function will take as its only argument. This allows avoiding having to reparse the formatters and go through the template each time things are processed.
  2. Call .render(data) on the FormatPieces<T>.

A very small example with Strings passed in, although you can pass an object of any type:

use funcfmt::{fm, FormatMap, Render, ToFormatPieces};

fn main() {
    let formatters = FormatMap::from([
        fm!("foo", |data| Some(format!("foo: {data}"))),
        fm!("bar", |data| Some(format!("bar: {data}"))),
        fm!("baz", |data| Some(format!("baz: {data}"))),
    ]);

    let fp = formatters.to_format_pieces("{foo}, {bar}").unwrap();

    // foo: some data, bar: some data
    let data_one = String::from("some data");
    println!("{}", fp.render(&data_one).unwrap());

    // foo: other data, bar: other data
    // note that this doesn't require processing the format again
    let data_two = String::from("other data");
    println!("{}", fp.render(&data_two).unwrap());
}

Dependencies

~0.4–1MB
~21K SLoC