pub struct Template<const O: char, const C: char> { /* private fields */ }Expand description
A compiled template ready for rendering.
Templates are parameterized by two characters representing the opening (O)
and closing (C) delimiters. Common choices are {/} or </>.
Templates are compiled once and can be rendered multiple times with different contexts, making them efficient for repeated use.
§Type Parameters
O- The opening delimiter character (e.g.,'{')C- The closing delimiter character (e.g.,'}')
§Examples
use figura::{Template, Context, Value};
use std::collections::HashMap;
// Using default delimiters
let tmpl = Template::<'{', '}'>::compile("Hello {name}!").unwrap();
let mut ctx = HashMap::new();
ctx.insert("name", Value::static_str("World"));
assert_eq!(tmpl.format(&ctx).unwrap(), "Hello World!");Implementations§
Source§impl<const O: char, const C: char> Template<O, C>
impl<const O: char, const C: char> Template<O, C>
Sourcepub fn compile(input: impl AsRef<str>) -> Result<Self, TemplateError>
pub fn compile(input: impl AsRef<str>) -> Result<Self, TemplateError>
Compiles a template string using the default parser.
This is the most common way to create a template. It uses the DefaultParser
which supports variable substitution, repeating patterns, and conditional logic.
§Arguments
input- The template string to compile
§Returns
Ok(Template)- A compiled template ready for renderingErr(TemplateError)- If the template syntax is invalid
§Errors
Returns a TemplateError if:
- A delimiter is not properly closed
- A directive cannot be parsed
§Examples
use figura::{Template, Context, Value};
use std::collections::HashMap;
// Variable substitution
let tmpl = Template::<'{', '}'>::compile("Hello {name}!").unwrap();
let mut ctx = HashMap::new();
ctx.insert("name", Value::static_str("World"));
assert_eq!(tmpl.format(&ctx).unwrap(), "Hello World!");
// Repeating patterns
let tmpl = Template::<'{', '}'>::compile("{'*':count}").unwrap();
let mut ctx = HashMap::new();
ctx.insert("count", Value::Int(3));
assert_eq!(tmpl.format(&ctx).unwrap(), "***");
// Conditionals
let tmpl = Template::<'{', '}'>::compile("{x > 5 ? 'big' : 'small'}").unwrap();
let mut ctx = HashMap::new();
ctx.insert("x", Value::Int(10));
assert_eq!(tmpl.format(&ctx).unwrap(), "big");Sourcepub fn compile_with_parser<P: Parser>(
input: &str,
) -> Result<Self, TemplateError>
pub fn compile_with_parser<P: Parser>( input: &str, ) -> Result<Self, TemplateError>
Compiles a template string using a custom parser.
This method allows you to use a custom parser implementation for specialized
template syntax or custom directives. The parser must implement the Parser trait.
§Type Parameters
P- A type implementing theParsertrait
§Arguments
input- The template string to compile
§Returns
Ok(Template)- A compiled template ready for renderingErr(TemplateError)- If the template syntax is invalid
§Errors
Returns a TemplateError if:
- A delimiter is not properly closed
- The custom parser cannot parse a directive
§Examples
use figura::{Template, DefaultParser, Context, Value};
use std::collections::HashMap;
// Using the default parser explicitly
let tmpl = Template::<'{', '}'>::compile_with_parser::<DefaultParser>(
"Hello {name}!"
).unwrap();
let mut ctx = HashMap::new();
ctx.insert("name", Value::static_str("Alice"));
assert_eq!(tmpl.format(&ctx).unwrap(), "Hello Alice!");For custom parser implementations, implement the Parser trait:
use figura::{Parser, Token, Directive};
struct MyCustomParser;
impl Parser for MyCustomParser {
fn parse(tokens: &[Token]) -> Option<Box<dyn Directive>> {
// Your custom parsing logic here
None
}
}Sourcepub fn format(&self, ctx: &Context) -> Result<String, DirectiveError>
pub fn format(&self, ctx: &Context) -> Result<String, DirectiveError>
Renders the template using the provided context.
This method executes all directives in the template and concatenates their results into a final string. It pre-allocates a reasonable capacity to minimize allocations during rendering.
§Arguments
ctx- A reference to the context containing variable values
§Returns
Ok(String)- The rendered template outputErr(DirectiveError)- If any directive fails (e.g., missing variable, type mismatch)
§Errors
Returns a DirectiveError if:
- A referenced variable is not found in the context
- A variable has an incompatible type for the operation
- A literal value cannot be parsed as the required type
§Examples
use figura::{Template, Context, Value};
use std::collections::HashMap;
let tmpl = Template::<'{', '}'>::compile("Hi {name}!").unwrap();
let mut ctx = HashMap::new();
ctx.insert("name", Value::static_str("Alice"));
let output = tmpl.format(&ctx).unwrap();
assert_eq!(output, "Hi Alice!");