Skip to content

codebysd/rs_tpl

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

rs_tpl

String templating in Rust with support for variable substitution, escaping, nesting, and recursive resolution.

Quick Start

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!");

Short Example

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!");

Advanced Example

Nested Variables and Recursive Resolution

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");

Custom Parser Configuration

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!");

Default Values and Error Handling

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!");

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

String templating in Rust

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages