A minimal text template engine that allows named placeholders within your templates.
There are two necessary pieces in order to parse a template:
Placeholders are defined within certain boundaries and will be replaced once the template is parsed.
Let's define a template with placeholders named first
and second
:
rust
let template = Template::new("Hello {{first}} {{second}}!");
Templates use the handlebars syntax as boundaries by default, but can be overridden:
rust
let template = Template::new_with_placeholder("Hello $[first]] $[second]!", "$[", "]");
Context is the data structure that will be used to replace your placeholders with real data.
You can think of your placeholder as a key within a HashMap
or the name of a field within a
struct
. In fact, these are the two types of context supported by this library:
Each placeholder should be a key
with an associated value
that can be converted into a str
.
The following methods are available with a HashMap
:
fill_with_hashmap
fill_with_hashmap_strict
which returns a Error::PlaceholderError
when:
```rust use text_placeholder::Template; use std::collections::HashMap;
let default_template = Template::new("Hello {{first}} {{second}}!");
let mut table = HashMap::new(); table.insert("first", "text"); table.insert("second", "placeholder");
asserteq!(defaulttemplate.fillwithhashmap(&table), "Hello text placeholder!");
// We can also specify our own boundaries:
let customtemplate = Template::newwith_placeholder("Hello $[first]] $[second]!", "$[", "]");
asserteq!(defaulttemplate.fillwithhashmap(&table), "Hello text placeholder!"); ```
Allow structs that implement the serde::Serialize
trait to be used as context.
This is an optional feature that depends on serde
. In order to enable it add the following to your Cargo.toml
file:
toml
[dependencies]
text_placeholder = { version = "0.3.1", features = ["struct_context"] }
Each placeholder should be a field
in your struct
with an associated value
that can be converted into a str
.
The following methods are available with a struct
:
fill_with_struct
fill_with_struct_strict
which returns a Error::PlaceholderError
when:
```rust use text_placeholder::Template;
struct Context { first: String, second: String }
let defaulttemplate = Template::new("Hello {{first}} {{second}}!"); let context = Context { first: "text".tostring(), second: "placeholder".to_string() };
asserteq!(defaulttemplate.fillwithstruct(&context), "Hello text placeholder!");
// We can also specify our own boundaries:
let customtemplate = Template::newwith_placeholder("Hello $[first]] $[second]!", "$[", "]");
asserteq!(defaulttemplate.fillwithstruct(&context), "Hello text placeholder!"); ```