10 releases

new 0.3.7 Dec 13, 2024
0.3.5 Sep 15, 2024
0.3.3 Jun 29, 2024
0.3.0 Aug 31, 2023
0.1.2 Mar 3, 2022

#17 in Template engine

Download history 26052/week @ 2024-08-23 19667/week @ 2024-08-30 23312/week @ 2024-09-06 13207/week @ 2024-09-13 22155/week @ 2024-09-20 29357/week @ 2024-09-27 14189/week @ 2024-10-04 24547/week @ 2024-10-11 24322/week @ 2024-10-18 22367/week @ 2024-10-25 16030/week @ 2024-11-01 28184/week @ 2024-11-08 48633/week @ 2024-11-15 18867/week @ 2024-11-22 24903/week @ 2024-11-29 29491/week @ 2024-12-06

135,891 downloads per month
Used in 11 crates (6 directly)

BSD-2-Clause OR Apache-2.0

87KB
2K SLoC

subst

Shell-like variable substitution for strings and byte strings.

Features

  • Perform substitution in &str or in &[u8].
  • Provide a custom map of variables or use environment variables.
    • Support for indexmap (requires the indexmap feature).
  • Short format: "Hello $name!"
  • Long format: "Hello ${name}!"
  • Default values: "Hello ${name:person}!"
  • Recursive substitution in default values: "${XDG_CONFIG_HOME:$HOME/.config}/my-app/config.toml"
  • Perform substitution on all string values in TOML, JSON or YAML data (optional, requires the toml, json or yaml feature).

Variable names can consist of alphanumeric characters and underscores. They are allowed to start with numbers.

If you want to quickly perform substitution on a string, use substitute() or substitute_bytes().

It is also possible to use one of the template types. The templates parse the source string or bytes once, and can be expanded as many times as you want. There are four different template types to choose from:

Examples

The substitute() function can be used to perform substitution on a &str. The variables can either be a HashMap or a BTreeMap.

let mut variables = HashMap::new();
variables.insert("name", "world");
assert_eq!(subst::substitute("Hello $name!", &variables)?, "Hello world!");

The variables can also be taken directly from the environment with the Env map.

assert_eq!(
  subst::substitute("$XDG_CONFIG_HOME/my-app/config.toml", &subst::Env)?,
  "/home/user/.config/my-app/config.toml",
);

Substitution can also be done on byte strings using the substitute_bytes() function.

let mut variables = HashMap::new();
variables.insert("name", b"world");
assert_eq!(subst::substitute_bytes(b"Hello $name!", &variables)?, b"Hello world!");

You can also parse a template once and expand it multiple times:

let template = subst::Template::from_str("Welcome to our hair salon, $name!")?;
for name in ["Scrappy", "Coco"] {
  let variables: HashMap<_, _> = [("name", name)].into_iter().collect();
  let message = template.expand(&variables)?;
  println!("{}", message);
}

Dependencies

~1.2–2.2MB
~36K SLoC