Skip to main content

Template

Struct Template 

Source
pub struct Template { /* private fields */ }
Expand description

A parsed template ready for rendering.

Templates can be loaded from files or parsed from in-memory strings. Variable declarations from frontmatter are used for context validation before rendering.

Implementations§

Source§

impl Template

Source

pub fn render_ctx(&self, ctx: &Context) -> Result<String, TemplateError>

Render the template with the given context (strict mode).

Validates the context against frontmatter declarations:

  • Missing declared parameters → error
  • Type mismatches → error
  • Extra undeclared parameters → error

Use render_ctx_allowing_extra to permit undeclared parameters (e.g. when sharing a context across templates).

§Errors

Returns TemplateError if validation fails or a rendering error occurs.

Source

pub fn render_ctx_allowing_extra( &self, ctx: &Context, ) -> Result<String, TemplateError>

Render the template, allowing extra (undeclared) parameters.

Like render_ctx, but extra context keys that aren’t declared in frontmatter are silently ignored instead of producing an error. Useful when forwarding a shared context to multiple templates.

§Errors

Returns TemplateError if validation fails or a rendering error occurs.

Source

pub fn render_empty(&self) -> Result<String, TemplateError>

Render a template that takes no user-provided parameters.

If the template declares parameters, those must all have defaults. Calling render_empty() on a template with required (no-default) parameters returns TemplateError::MissingParams.

This is more efficient than render(&empty_struct) (no serde overhead) and more explicit than render_ctx(&Context::new()).

§Examples
use md_tmpl_core::Template;

// No params — renders as-is
let tmpl = Template::from_source(
    r#"---
params: []
---
Hello world!"#,
)
.unwrap();
assert_eq!(tmpl.render_empty().unwrap(), "Hello world!");

// All params have defaults
let tmpl = Template::from_source(
    r#"---
params:
  - greeting = str := "Hi"
---
{{ greeting }}!"#,
)
.unwrap();
assert_eq!(tmpl.render_empty().unwrap(), "Hi!");
§Errors

Returns TemplateError::MissingParams if any declared parameter lacks a default value.

Source

pub fn render_empty_into( &self, output: &mut String, ) -> Result<(), TemplateError>

Like render_empty, but appends to an existing buffer.

§Errors

Returns TemplateError::MissingParams if any declared parameter lacks a default value.

Source

pub fn render_ctx_into( &self, ctx: &Context, output: &mut String, ) -> Result<(), TemplateError>

Render the template directly into an existing String buffer.

Unlike render_ctx, this appends to output without allocating a new String. Useful when composing multiple template outputs into a single buffer.

§Errors

Returns TemplateError if validation fails or a rendering error occurs. On error, output may contain partial results.

Source

pub fn render_ctx_into_allowing_extra( &self, ctx: &Context, output: &mut String, ) -> Result<(), TemplateError>

Like render_ctx_into, but allows extra (undeclared) parameters.

§Errors

Returns TemplateError if validation fails or a rendering error occurs.

Source

pub fn render_ctx_unchecked( &self, ctx: &Context, ) -> Result<String, TemplateError>

Render the template without context validation.

Skips the parameter presence, type, and extra-key checks that render_ctx performs on every call. This is a safe operation — rendering errors (e.g. undefined variable) are still reported via Err — but the upfront validation overhead is removed.

Use this when the context is known-good (e.g. constructed from a strongly-typed params struct, or pre-validated once at startup).

§Errors

Returns TemplateError if a rendering error occurs (e.g. undefined variable, filter error).

Source

pub fn render_ctx_into_unchecked( &self, ctx: &Context, output: &mut String, ) -> Result<(), TemplateError>

Render into a buffer without context validation.

Like render_ctx_unchecked, but appends to an existing buffer.

§Errors

Returns TemplateError if a rendering error occurs.

Source

pub fn render_ctx_cached<S>( &self, ctx: &Context, cache: &TemplateCache<S>, ) -> Result<String, TemplateError>
where S: BuildHasher + Send + Sync,

Render the template using a TemplateCache for include resolution.

Like render_ctx, but included templates are resolved through the cache — unchanged includes are not re-read or re-compiled. This is the recommended rendering path for hot-reload scenarios where templates are re-rendered frequently.

§Errors

Returns TemplateError if validation fails or a rendering error occurs.

Source

pub fn render_ctx_cached_allowing_extra<S>( &self, ctx: &Context, cache: &TemplateCache<S>, ) -> Result<String, TemplateError>
where S: BuildHasher + Send + Sync,

Render with caching, allowing extra parameters in the context.

Like render_ctx_cached() but does not reject parameters not declared in the template frontmatter.

§Errors

Returns TemplateError if validation fails or a rendering error occurs.

Source§

impl Template

Source

pub fn render<T>(&self, value: &T) -> Result<String, TemplateError>
where T: Serialize + 'static,

Render the template from any Serialize struct.

Struct fields become template variables — no manual Context construction needed.

On the first call with a given T, the context is fully validated against frontmatter declarations. If validation passes, TypeId::of::<T>() is cached so that subsequent calls with the same concrete type skip validation entirely. This gives the safety of runtime type-checking with near-zero amortized cost.

§Errors

Returns TemplateError if serialization fails, the value is not a struct/map, or rendering encounters an error.

§Examples
use md_tmpl_core::Template;
use serde::Serialize;

#[derive(Serialize)]
struct Data {
    name: String,
    count: i64,
}

let tmpl = Template::from_source(
    r#"---
params: [name = str, count = int]
---
{{ name }} has {{ count }} items"#,
)
.unwrap();
let output = tmpl
    .render(&Data {
        name: "Alice".into(),
        count: 3,
    })
    .unwrap();
assert_eq!(output, "Alice has 3 items");
Source

pub fn render_into<T>( &self, value: &T, output: &mut String, ) -> Result<(), TemplateError>
where T: Serialize + 'static,

Like render, but appends output into an existing buffer.

§Errors

Returns TemplateError if serialization fails, the value is not a struct/map, or rendering encounters an error.

Source§

impl Template

Source

pub fn from_file(path: &Path) -> Result<Template, TemplateError>

Load a template from a file, stripping YAML frontmatter.

§Errors

Returns TemplateError::Io if the file cannot be read.

Source

pub fn from_source(source: &str) -> Result<Template, TemplateError>

Parse a template from an in-memory string (no include resolution).

§Errors

Returns TemplateError::Syntax if the body contains a syntax error.

Source

pub fn compile( source: &str, options: CompileOptions<'_>, ) -> Result<(Template, Frontmatter), TemplateError>

Parse a template from source with compile options, returning both the template and its frontmatter.

This is the unified entry point that replaces the family of from_source_* constructors.

§Examples
use md_tmpl_core::{CompileOptions, Template};

let (tmpl, fm) = Template::compile(
    r#"---
params: [name = str]
---
Hello {{ name }}!"#,
    CompileOptions::default(),
)
.unwrap();
§Errors

Returns TemplateError::Syntax if the body contains a syntax error.

Source

pub fn compile_file( path: &Path, options: CompileOptions<'_>, ) -> Result<(Template, Frontmatter), TemplateError>

Load a template from a file with compile options, returning both the template and its frontmatter.

The file’s parent directory is used as the base directory for include resolution unless overridden in options.

§Examples
use std::path::Path;

use md_tmpl_core::{CompileOptions, Template};

let (tmpl, fm) =
    Template::compile_file(Path::new("template.tmpl.md"), CompileOptions::default()).unwrap();
§Errors

Returns TemplateError::Io if the file cannot be read.

Source

pub fn defaults(&self) -> HashMap<String, Value>

Returns default values for all params that have them.

Source

pub fn default(&self, name: &str) -> Option<&Value>

Returns the default value for a single parameter, if it has one.

Source

pub fn defaults_context(&self) -> Context

Returns a Context pre-filled with all default values.

Use this as a starting point, then override only the params you need:

let tmpl = Template::from_source(
    r#"---
params:
  - name = str
  - count = int := 5
---
{{ name }} ({{ count }})"#,
)
.unwrap();
let mut ctx = tmpl.defaults_context();
ctx.set("name", "Alice"); // count already has default 5
assert_eq!(tmpl.render_ctx(&ctx).unwrap(), "Alice (5)");
Source

pub fn body(&self) -> &str

Return the raw template body text (after frontmatter stripping).

Useful for compile-time validation and macro integration.

Source

pub fn name(&self) -> Option<&str>

Returns the template’s name, if defined in frontmatter.

Source

pub fn description(&self) -> Option<&str>

Returns the template’s description, if defined in frontmatter.

Source

pub fn set_max_include_depth(&mut self, depth: usize)

Set the maximum include depth for rendering this template.

Source

pub fn with_max_include_depth(self, depth: usize) -> Template

Set the maximum include depth for rendering this template (builder style).

Source

pub fn declarations(&self) -> &[VarDecl]

Return the declared variables from frontmatter.

Used by generated param structs to validate that a reloaded template still matches the compile-time variable declarations.

Source

pub fn base_dir(&self) -> Option<&Path>

Returns the base directory used for resolving filesystem {% include %} paths.

Source

pub fn consts(&self) -> Arc<HashMap<String, Value>>

Returns the constants defined in this template’s frontmatter.

Constants are defined with consts: in frontmatter and are automatically available during rendering without being passed in the context.

§Examples
use md_tmpl_core::Template;

let tmpl = Template::from_source(
    r#"---
consts:
  - MAX = int := 100

params: []
---
{{ MAX }}"#,
)
.unwrap();
let consts = tmpl.consts();
assert_eq!(consts.get("MAX").unwrap().as_int(), Some(100));
Source

pub fn consts_ref(&self) -> &HashMap<String, Value>

Returns a borrowed reference to the constants defined in this template’s frontmatter, avoiding the Arc clone of consts.

Source

pub fn imported_consts(&self) -> Arc<HashMap<String, Value>>

Returns the imported constants (from {% import %} directives).

These are constants imported from other template files and are automatically available during rendering alongside regular constants.

Source

pub fn imported_consts_ref(&self) -> &HashMap<String, Value>

Returns a borrowed reference to the imported constants, avoiding the Arc clone of imported_consts.

Source

pub fn source_hash(&self) -> u64

Content hash of the raw source — use to detect unchanged files on hot-reload without re-parsing.

Same source → same hash. Different source → (very likely) different hash. This is a fast non-cryptographic hash, not suitable for security purposes.

Source

pub fn validate_declarations( &self, expected: &[VarDecl], ) -> Result<(), TemplateError>

Validate that a (possibly reloaded) template’s variable declarations match an expected set.

Call this after re-loading a template from disk to ensure that nobody (e.g. an autonomous agent editing markdown files at runtime) has modified the params: block in the frontmatter.

The template body may be changed freely — only the variable declarations must remain stable.

§Errors

Returns TemplateError::DeclarationsMutated with a human-readable diff if the declarations don’t match.

Trait Implementations§

Source§

impl Clone for Template

Source§

fn clone(&self) -> Template

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Template

Source§

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

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

impl<'de> Deserialize<'de> for Template

Available on crate feature serde only.

Deserialize always fails — Template must be constructed from source.

This impl exists solely to satisfy derive bounds on macro-generated parameter structs. Actual deserialization of a compiled template is not meaningful.

Source§

fn deserialize<D>( deserializer: D, ) -> Result<Template, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Eq for Template

Source§

impl From<&Template> for Value

Source§

fn from(t: &Template) -> Value

Converts to this type from the input type.
Source§

impl From<Template> for Value

Source§

fn from(t: Template) -> Value

Converts to this type from the input type.
Source§

impl PartialEq for Template

Two templates are considered equal if they were compiled from the same source (compared via non-cryptographic 64-bit hash).

Note: This is an approximate comparison — different sources that produce the same hash would incorrectly compare as equal. Do not use Template as a HashMap key or rely on Eq for deduplication in security-sensitive contexts. For exact source comparison, compare body() and declarations().

Source§

fn eq(&self, other: &Template) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for Template

Available on crate feature serde only.

Serialize a Template as a source-hash identifier.

Templates embedded in macro-generated parameter structs need Serialize to satisfy derive bounds, even when the struct is never actually serialized. The hash lets debug/logging code produce something readable.

Source§

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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.