String templating in Rust with support for variable substitution, escaping, nesting, and recursive resolution.
Add to your Cargo.toml:
[dependencies]
rs_tpl = "0.1.0"Use the tpl! macro for simple templating:
use rs_tpl::tpl;
let result = tpl!("Hello ${name}!", [("name", "World")]);
assert_eq!(result, "Hello World!");use rs_tpl::{Parser, Resolver};
// Parse a template
let parser = Parser::default();
let template = parser.parse("Hello ${name}, welcome to ${place}!".chars()).unwrap();
// Create a resolver with variables
let resolver = Resolver::from([
("name", "there"),
("place", "Rust"),
]);
// Render the template
let output = template.render(&resolver).unwrap();
assert_eq!(output, "Hello there, welcome to Rust!");use rs_tpl::{Parser, Resolver};
// Template with nested variables
let input = "The ${fish} were sighted ${${direction}-${distance}} of the coast";
let parser = Parser::default();
let template = parser.parse(input.chars()).unwrap();
// Resolver with recursive capability - values contain more templates
let base_resolver = Resolver::from([
("fish", "${count} ${species}"),
("count", "school of"),
("species", "salmon"),
("direction", "north"),
("distance", "east"),
("north-east", "northeast"),
]);
let recursive_resolver = base_resolver.recursive(&parser, 3);
let output = template.render(&recursive_resolver).unwrap();
assert_eq!(output, "The school of salmon were sighted northeast of the coast");use rs_tpl::Parser;
// Custom delimiters and escape character
let parser = Parser::new("%<", ">", '#').unwrap();
let template = parser.parse("Hello #%<name#> %<name>!".chars()).unwrap();
let resolver = Resolver::from([("name", "World")]);
let output = template.render(&resolver).unwrap();
assert_eq!(output, "Hello %<name> World!");use rs_tpl::{Parser, Resolver};
let parser = Parser::default();
let template = parser.parse("Hello ${name}, ${missing}!".chars()).unwrap();
// Resolver with default value for missing variables
let resolver = Resolver::from([("name", "Alice")])
.with_default("N/A");
let output = template.render(&resolver).unwrap();
assert_eq!(output, "Hello Alice, N/A!");This project is licensed under the MIT License - see the LICENSE file for details.