Template

Struct Template 

Source
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>

Source

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 rendering
  • Err(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");
Source

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 the Parser trait
§Arguments
  • input - The template string to compile
§Returns
  • Ok(Template) - A compiled template ready for rendering
  • Err(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
    }
}
Source

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 output
  • Err(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!");

Trait Implementations§

Source§

impl<const C: char, const O: char> Debug for Template<O, C>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<const O: char, const C: char> Freeze for Template<O, C>

§

impl<const O: char, const C: char> !RefUnwindSafe for Template<O, C>

§

impl<const O: char, const C: char> !Send for Template<O, C>

§

impl<const O: char, const C: char> !Sync for Template<O, C>

§

impl<const O: char, const C: char> Unpin for Template<O, C>

§

impl<const O: char, const C: char> !UnwindSafe for Template<O, C>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.