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
impl Template
Sourcepub fn render_ctx(&self, ctx: &Context) -> Result<String, TemplateError>
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.
Sourcepub fn render_ctx_allowing_extra(
&self,
ctx: &Context,
) -> Result<String, TemplateError>
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.
Sourcepub fn render_empty(&self) -> Result<String, TemplateError>
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.
Sourcepub fn render_empty_into(
&self,
output: &mut String,
) -> Result<(), TemplateError>
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.
Sourcepub fn render_ctx_into(
&self,
ctx: &Context,
output: &mut String,
) -> Result<(), TemplateError>
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.
Sourcepub fn render_ctx_into_allowing_extra(
&self,
ctx: &Context,
output: &mut String,
) -> Result<(), TemplateError>
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.
Sourcepub fn render_ctx_unchecked(
&self,
ctx: &Context,
) -> Result<String, TemplateError>
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).
Sourcepub fn render_ctx_into_unchecked(
&self,
ctx: &Context,
output: &mut String,
) -> Result<(), TemplateError>
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.
Sourcepub fn render_ctx_cached<S>(
&self,
ctx: &Context,
cache: &TemplateCache<S>,
) -> Result<String, TemplateError>
pub fn render_ctx_cached<S>( &self, ctx: &Context, cache: &TemplateCache<S>, ) -> Result<String, TemplateError>
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.
Sourcepub fn render_ctx_cached_allowing_extra<S>(
&self,
ctx: &Context,
cache: &TemplateCache<S>,
) -> Result<String, TemplateError>
pub fn render_ctx_cached_allowing_extra<S>( &self, ctx: &Context, cache: &TemplateCache<S>, ) -> Result<String, TemplateError>
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
impl Template
Sourcepub fn render<T>(&self, value: &T) -> Result<String, TemplateError>where
T: Serialize + 'static,
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");Sourcepub fn render_into<T>(
&self,
value: &T,
output: &mut String,
) -> Result<(), TemplateError>where
T: Serialize + 'static,
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
impl Template
Sourcepub fn from_file(path: &Path) -> Result<Template, TemplateError>
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.
Sourcepub fn from_source(source: &str) -> Result<Template, TemplateError>
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.
Sourcepub fn compile(
source: &str,
options: CompileOptions<'_>,
) -> Result<(Template, Frontmatter), TemplateError>
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.
Sourcepub fn compile_file(
path: &Path,
options: CompileOptions<'_>,
) -> Result<(Template, Frontmatter), TemplateError>
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.
Sourcepub fn defaults(&self) -> HashMap<String, Value>
pub fn defaults(&self) -> HashMap<String, Value>
Returns default values for all params that have them.
Sourcepub fn default(&self, name: &str) -> Option<&Value>
pub fn default(&self, name: &str) -> Option<&Value>
Returns the default value for a single parameter, if it has one.
Sourcepub fn defaults_context(&self) -> Context
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)");Sourcepub fn body(&self) -> &str
pub fn body(&self) -> &str
Return the raw template body text (after frontmatter stripping).
Useful for compile-time validation and macro integration.
Sourcepub fn description(&self) -> Option<&str>
pub fn description(&self) -> Option<&str>
Returns the template’s description, if defined in frontmatter.
Sourcepub fn set_max_include_depth(&mut self, depth: usize)
pub fn set_max_include_depth(&mut self, depth: usize)
Set the maximum include depth for rendering this template.
Sourcepub fn with_max_include_depth(self, depth: usize) -> Template
pub fn with_max_include_depth(self, depth: usize) -> Template
Set the maximum include depth for rendering this template (builder style).
Sourcepub fn declarations(&self) -> &[VarDecl]
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.
Sourcepub fn base_dir(&self) -> Option<&Path>
pub fn base_dir(&self) -> Option<&Path>
Returns the base directory used for resolving filesystem {% include %} paths.
Sourcepub fn consts(&self) -> Arc<HashMap<String, Value>>
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));Sourcepub fn consts_ref(&self) -> &HashMap<String, Value>
pub fn consts_ref(&self) -> &HashMap<String, Value>
Sourcepub fn imported_consts(&self) -> Arc<HashMap<String, Value>>
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.
Sourcepub fn imported_consts_ref(&self) -> &HashMap<String, Value>
pub fn imported_consts_ref(&self) -> &HashMap<String, Value>
Returns a borrowed reference to the imported constants, avoiding
the Arc clone of imported_consts.
Sourcepub fn source_hash(&self) -> u64
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.
Sourcepub fn validate_declarations(
&self,
expected: &[VarDecl],
) -> Result<(), TemplateError>
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<'de> Deserialize<'de> for Template
Available on crate feature serde only.Deserialize always fails — Template must be constructed from source.
impl<'de> Deserialize<'de> for Template
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>,
fn deserialize<D>(
deserializer: D,
) -> Result<Template, <D as Deserializer<'de>>::Error>where
D: Deserializer<'de>,
impl Eq for Template
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).
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§impl Serialize for Template
Available on crate feature serde only.Serialize a Template as a source-hash identifier.
impl Serialize for Template
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,
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>where
S: Serializer,
Auto Trait Implementations§
impl !Freeze for Template
impl RefUnwindSafe for Template
impl Send for Template
impl Sync for Template
impl Unpin for Template
impl UnsafeUnpin for Template
impl UnwindSafe for Template
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.