Template

Struct Template 

Source
#[non_exhaustive]
pub struct Template<T, A> { /* private fields */ }
Expand description

A compiled representation of a template string with expression syntax defined by an Ast.

Compile a template by providing a template string and an Ast using Template::compile. Once you have a template, render it using an appropriate Manifest:

Templates are immutable, but you can deconstruct and reconstruct a template using its IntoIterator and FromIterator implementations.

§Type parameters

A Template is generic over two type parameters:

  • T: the template text type. For example, T = &str or T = Box<str>. These cases are aliased in BorrowedTemplate and OwnedTemplate. T can be any type which is From<&'fmt str> (when compiling) and AsRef<str> (when rendering).
  • A: the compiled format of the expression. When compiling from a template string, this must implement Ast.

For example, if you want ownership:

use mufmt::Template;
let template_str = "A {0}".to_owned();

// A template which owns all of its own data:
// - text stored as `String`
// - expressions compiled as `usize`
let template = Template::<String, usize>::compile(&template_str).unwrap();

// we can safely drop the original data
drop(template_str);

// and still use the template
let mfst = vec!["cat"];
assert_eq!(template.render(&mfst).unwrap(), "A cat");

Or if you want to borrow:

let template_str = "A {key}".to_owned();

// A template which borrows all of its data from the template string
let template = Template::<&str, &str>::compile(&template_str).unwrap();

// drop(template_str); // uncomment for compile error

let mfst = HashMap::from([("key", "cat")]);
assert_eq!(template.render(&mfst).unwrap(), "A cat");

§Template spans

A template is internally a Vec of Spans with additional metadata.

Access the spans with Template::spans.

let template = Template::<&str, usize>::compile("Items {1} and {12}").unwrap();
// the implementation of `len` and `nth` efficient
assert_eq!(template.spans().len(), 4);
assert_eq!(template.spans().get(3), Some(&Span::Expr(12)));

Then, modify the template by decomposing it into spans and then reconstructing it.

let mapped_template: Template<&str, usize> = template
    // a template can be converted into an iterator of `Span`s.
    .into_iter()
    .map(|span| match span {
        Span::Text(t) => Span::Text(t),
        Span::Expr(b) => Span::Expr(b.max(4)),
    })
    // a template can be constructed from an iterator of `Span`s.
    .collect();
assert_eq!(mapped_template.spans().get(1), Some(&Span::Expr(4)));

Manually construct a template from an iterator of Spans.

let template: Template<&'static str, usize> =
    [Span::Text("Hello "), Span::Expr(2), Span::Text("!")]
        .into_iter()
        .collect();

let mfst = ["Eero", "Aino", "Maija"];

assert_eq!(template.render(&mfst).unwrap(), "Hello Maija!");

Implementations§

Source§

impl<T, A> Template<T, A>

Source

pub fn compile<'fmt>(s: &'fmt str) -> Result<Self, SyntaxError<A::Error>>
where A: Ast<'fmt>, T: From<&'fmt str>,

Compile the provided template string, interpreting the expressions using the Ast.

Source

pub fn render<M>(&self, mfst: &M) -> Result<String, M::Error>
where T: AsRef<str>, M: ManifestMut<A>,

A convenience function to render directly into a newly allocated String.

This is equivalent to allocating a new String yourself and writing into it with render_fmt.

Source

pub fn render_io<M, W>( &self, mfst: &M, writer: W, ) -> Result<(), IORenderError<M::Error>>
where T: AsRef<[u8]>, M: ManifestMut<A>, W: Write,

Write the compiled template into the provided io::Write implementation.

The writer is not flushed unless the Manifest implementation overrides the default Manifest::write_io implementation to manually flush the writer.

Source

pub fn render_fmt<M, W>( &self, mfst: &M, writer: W, ) -> Result<(), FmtRenderError<M::Error>>
where T: AsRef<str>, M: ManifestMut<A>, W: Write,

Write the compiled template into the provided fmt::Write implementation.

Source

pub fn spans(&self) -> &[Span<T, A>]

Returns a slice of the template spans.

If this template was compiled using Template::compile, the spans will satisfy precise text breaking rules.

Trait Implementations§

Source§

impl<T: Clone, A: Clone> Clone for Template<T, A>

Source§

fn clone(&self) -> Template<T, A>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug, A: Debug> Debug for Template<T, A>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<T, A> FromIterator<Span<T, A>> for Template<T, A>

Source§

fn from_iter<I: IntoIterator<Item = Span<T, A>>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl<T, A> IntoIterator for Template<T, A>

Source§

type Item = Span<T, A>

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<<Template<T, A> as IntoIterator>::Item>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T, A> Freeze for Template<T, A>

§

impl<T, A> RefUnwindSafe for Template<T, A>

§

impl<T, A> Send for Template<T, A>
where T: Send, A: Send,

§

impl<T, A> Sync for Template<T, A>
where T: Sync, A: Sync,

§

impl<T, A> Unpin for Template<T, A>
where T: Unpin, A: Unpin,

§

impl<T, A> UnwindSafe for Template<T, A>
where T: UnwindSafe, A: UnwindSafe,

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.