1 unstable release
Uses old Rust 2015
0.1.0 | Sep 5, 2018 |
---|
#18 in #template-string
31 downloads per month
13KB
216 lines
Simple text template engine for rust
This library implements text templates with named placeholder elements like
Hello ${title }${name}
. The space after title is significant in the sense that
it is only included in the output if title is not empty. This is to prevent
two consecutive whitespaces for example if a person has no title.
Please see https://docs.rs/crate/text-template for API documentation.
Example
use text_template::*;
use std::collections::HashMap;
let template = Template::from("Hello ${title }${name}");
let mut values = HashMap::new();
values.insert("name", "Jane");
let text = template.fill_in(&values);
assert_eq!(text.to_string(), "Hello Jane");
assert_eq!(template.to_string(), "Hello ${title }${name}");
lib.rs
:
A Minimal Text Template Engine
Overview
This library implements templates consisting of text including named placeholders.
Placeholders are special character sequences: their names surrounded by ${
and }
.
The example Template Hello␣${name}
consists of the text Hello␣
and the placeholder name
.
Trailing and pending whitespace inside placeholder elements are significant and conditionally
included in the output if the value to be inserted for the placeholder is not empty. For
example ${title␣}${name}
may evaluate to Dr.␣X
or Y
while ${title}␣${name}
may evaluate to
Dr.␣X
or ␣Y
.
Templates are represented by the structure Template
.
The templates implementation of From<&str>
can be used to construct templates from strings.
Templates can be filled in by using fill_in
or try_fill_in
, which replace any
placeholders in the template by the given values. The returned Text
structure is simply
a wrapper type around Vec<&str>
and dereferences to it.
A text representation of the templates and the filled in results can be obtained by using to_string
.
This library only stores references to the given template strings. It allocates a Vec
to store a list of text and placeholder elements while parsing a template string. A template,
once created, can be used multiple times to fill in different sets of values.
Example
use text_template::*;
use std::collections::HashMap;
let template = Template::from("Hello ${title }${name}");
let mut values = HashMap::new();
values.insert("name", "Jane");
let text = template.fill_in(&values);
assert_eq!(text.to_string(), "Hello Jane");
assert_eq!(template.to_string(), "Hello ${title }${name}");