pub struct Template<'t> { /* private fields */ }
Expand description
A template is composed of tokens, which in turn can represent plain text or a named placeholder.
Implementations§
Source§impl<'t> Template<'t>
impl<'t> Template<'t>
Sourcepub fn new(text: &'t str) -> Self
pub fn new(text: &'t str) -> Self
Generates a Template with boundaries specified by the handlebars syntax,
this means that within the string "hello {{key}}"
we will have key
as a named placeholder.
Example:
let template = Template::new("Hello {{key}}!");
Sourcepub fn new_with_placeholder(text: &'t str, start: &'t str, end: &'t str) -> Self
pub fn new_with_placeholder(text: &'t str, start: &'t str, end: &'t str) -> Self
Generates a Template with boundaries specified by the start
and end
arguments.
Example:
let template = Template::new_with_placeholder("Hello [key]!", "[", "]");
Sourcepub fn fill_with_hashmap(&self, replacements: &HashMap<&str, &str>) -> String
pub fn fill_with_hashmap(&self, replacements: &HashMap<&str, &str>) -> String
Fill the template’s placeholders using the provided replacements
HashMap
in order to to derive values for the named placeholders.
Placeholders without an associated value will be replaced with an empty string.
For a version that generates an error in case a placeholder is missing see
Template::fill_with_hashmap_strict
.
Sourcepub fn fill_with_hashmap_strict(
&self,
replacements: &HashMap<&str, &str>,
) -> Result<String>
pub fn fill_with_hashmap_strict( &self, replacements: &HashMap<&str, &str>, ) -> Result<String>
Fill the template’s placeholders using the provided replacements HashMap
in order to to infer values for the named placeholders.
Placeholders without an associated value will result in a Error::PlaceholderError
.
For a version that does not generate an error in case a placeholder is missing see
Template::fill_with_hashmap
.
Sourcepub fn fill_with_function<'a, F>(&self, replacements: F) -> Result<String>
pub fn fill_with_function<'a, F>(&self, replacements: F) -> Result<String>
Fill the template’s placeholders using the provided replacements
function in order to to derive values for the named placeholders.
replacements
is a FnMut
which may modify its environment. The
key
parameter is borrowed from Template
, and so can be stored in the
enclosing scope.
Returned Cow<str>
may also be borrwed from the key
, the
environment, or be an owned String
that’s computed from the key or
derived in some other way.
Placeholders without an associated value (the function returns None
)
will result in a Error::PlaceholderError
.
This is the most general form of replacement; the other fill_with_
methods are implemented in terms of this method.
Example:
let template = Template::new("Hello {{first}} {{second}}!");
let mut idx = 0;
assert_eq!(
&*template.fill_with_function(
|key| {
idx += 1;
Some(Cow::Owned(format!("{key}-{idx}")))
})
.unwrap(),
"Hello first-1 second-2!"
);
assert_eq!(idx, 2);