pub struct Engine {
pub template_path: String,
pub render_cache: Mutex<Cache<String, String>>,
pub open_delim: String,
pub close_delim: String,
pub escape_html: bool,
pub custom_filters: HashMap<String, FilterFn>,
pub custom_tests: HashMap<String, TestFn>,
pub loader: Arc<dyn TemplateLoader>,
pub autoescape_extensions: Vec<String>,
pub lax_undefined: bool,
}Expand description
The main template rendering engine.
§Examples
use staticweaver::{Context, Engine};
use std::time::Duration;
let engine = Engine::new("templates", Duration::from_secs(60));
let mut ctx = Context::new();
ctx.set("who".to_string(), "world".to_string());
let out = engine.render_template("hello {{who}}", &ctx).unwrap();
assert_eq!(out, "hello world");Fields§
§template_path: StringPath to the template directory.
§Examples
use staticweaver::Engine;
use std::time::Duration;
let engine = Engine::new("templates", Duration::from_secs(60));
assert_eq!(engine.template_path, "templates");render_cache: Mutex<Cache<String, String>>Cache for rendered templates keyed by "{layout}:{ctx.hash()}".
Wrapped in Mutex (issue #36, v0.0.4) so Engine is Send + Sync
and render_page can take &self — making the engine sharable
across threads / async tasks via Arc<Engine> without the
Arc<Mutex<Engine>> envelope users previously had to write.
The lock is held only across the cache lookup or insert; the
expensive render work happens outside it.
§Examples
use staticweaver::Engine;
use std::time::Duration;
let engine = Engine::new("", Duration::from_secs(60));
assert_eq!(engine.render_cache.lock().unwrap().len(), 0);open_delim: StringOpening delimiter for template tags. Defaults to "{{".
§Examples
use staticweaver::Engine;
use std::time::Duration;
let engine = Engine::new("", Duration::from_secs(60));
assert_eq!(engine.open_delim, "{{");close_delim: StringClosing delimiter for template tags. Defaults to "}}".
§Examples
use staticweaver::Engine;
use std::time::Duration;
let engine = Engine::new("", Duration::from_secs(60));
assert_eq!(engine.close_delim, "}}");escape_html: boolWhen true, values substituted into templates are HTML-escaped
(&, <, >, ", '). Prefix a key with ! to opt out per-tag
(e.g. {{!content}} emits the raw value).
§Examples
use staticweaver::Engine;
use std::time::Duration;
let engine = Engine::new("", Duration::from_secs(60))
.with_html_escape(false);
assert!(!engine.escape_html);custom_filters: HashMap<String, FilterFn>User-registered filters keyed by name. Looked up before the
built-in filter set, so a custom filter can override a
built-in of the same name. Populate via Engine::add_filter.
§Examples
use staticweaver::Engine;
use std::sync::Arc;
use std::time::Duration;
let mut engine = Engine::new("", Duration::from_secs(60));
let _ = engine.add_filter(
"shout",
Arc::new(|s, _| Ok(s.to_uppercase())),
);
assert!(engine.custom_filters.contains_key("shout"));custom_tests: HashMap<String, TestFn>User-registered tests keyed by name. Looked up before the
built-in tests (defined, empty, none) so a custom test
can override a built-in of the same name. Populate via
Engine::add_test.
§Examples
use staticweaver::Engine;
use std::sync::Arc;
use std::time::Duration;
let mut engine = Engine::new("", Duration::from_secs(60));
let _ = engine.add_test("admin", Arc::new(|_v, _| Ok(true)));
assert!(engine.custom_tests.contains_key("admin"));loader: Arc<dyn TemplateLoader>Source of template content for render_page, partial
includes, and {{#extends}}. Defaults to an FsLoader
rooted at template_path. Override via
Engine::with_loader for in-memory or custom-backend
templates.
§Examples
use staticweaver::Engine;
use std::time::Duration;
let engine = Engine::new("templates", Duration::from_secs(60));
// The default loader is an FsLoader; the field exposes it
// as a trait object so callers can swap it freely.
assert!(engine.loader.load("missing").is_err());autoescape_extensions: Vec<String>File extensions (e.g. .html, .xml) for which
Engine::render_page auto-escapes substitutions.
Empty (default) = use the global escape_html setting
uniformly. When non-empty, layouts whose name ends with one
of these extensions auto-escape; everything else renders
raw. Matches Tera’s per-extension autoescape behaviour.
Populate via Engine::autoescape_on.
§Examples
use staticweaver::Engine;
use std::time::Duration;
let mut engine = Engine::new("", Duration::from_secs(60));
let _ = engine.autoescape_on(&[".html"]);
assert_eq!(engine.autoescape_extensions, vec![".html"]);lax_undefined: boolWhen true, an unresolved {{key}} substitution emits an
empty string instead of aborting the render with
EngineError::Render("Unresolved template tag: <key>").
Defaults to false (strict). Mirrors Jinja2’s “undefined”
mode and lets sites whose page templates reference variables
that not every page supplies build without per-page shims.
Toggle via Engine::with_lax_undefined. Issue #28.
Implementations§
Source§impl Engine
impl Engine
Sourcepub fn new(template_path: &str, cache_ttl: Duration) -> Self
pub fn new(template_path: &str, cache_ttl: Duration) -> Self
Creates a new Engine instance with HTML escaping enabled.
§Arguments
template_path- The path to the template directory.cache_ttl- Time-to-live for cached rendered templates.
§Examples
use staticweaver::engine::Engine;
use std::time::Duration;
let engine = Engine::new("templates", Duration::from_secs(3600));Sourcepub fn with_loader(loader: Arc<dyn TemplateLoader>, cache_ttl: Duration) -> Self
pub fn with_loader(loader: Arc<dyn TemplateLoader>, cache_ttl: Duration) -> Self
Constructs an engine that loads templates through loader
instead of the default filesystem backend. Use this when
you want in-memory templates (MemoryLoader), templates
stored in a database, embedded asset bundles, or any other
custom source.
template_path is set to the empty string in this
constructor — it’s only used by the default FsLoader,
which the custom loader replaces. Path-validation logic on
partial / extends names still applies.
§Examples
use staticweaver::engine::{Engine, MemoryLoader};
use staticweaver::Context;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
let mut store = HashMap::new();
let _ = store
.insert("hello".to_string(), "Hi, {{name}}!".to_string());
let mut engine = Engine::with_loader(
Arc::new(MemoryLoader::new(store)),
Duration::from_secs(60),
);
let mut ctx = Context::new();
ctx.set("name".to_string(), "Ada".to_string());
assert_eq!(
engine.render_page(&ctx, "hello").unwrap(),
"Hi, Ada!",
);Sourcepub fn autoescape_on(&mut self, extensions: &[&str]) -> &mut Self
pub fn autoescape_on(&mut self, extensions: &[&str]) -> &mut Self
Configures per-extension auto-escape policy for
Engine::render_page. When called with a non-empty list,
render_page auto-escapes ONLY for layouts whose name ends
with one of the listed suffixes; layouts with any other
extension render raw.
Mirrors Tera’s autoescape_on(vec![".html"]). The global
escape_html flag still applies to render_template
(which has no layout name to inspect).
Returns &mut Self for builder-style chaining.
§Examples
use staticweaver::{Context, Engine};
use staticweaver::engine::MemoryLoader;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
let mut store = HashMap::new();
let _ = store.insert("page.html".to_string(), "{{x}}".to_string());
let _ = store.insert("plain.txt".to_string(), "{{x}}".to_string());
let mut engine = Engine::with_loader(
Arc::new(MemoryLoader::new(store)),
Duration::from_secs(60),
);
engine.autoescape_on(&[".html"]);
let mut ctx = Context::new();
ctx.set("x".to_string(), "<b>".to_string());
// .html: escaped
assert_eq!(engine.render_page(&ctx, "page.html").unwrap(), "<b>");
// .txt: raw
assert_eq!(engine.render_page(&ctx, "plain.txt").unwrap(), "<b>");Sourcepub fn add_filter(&mut self, name: &str, filter: FilterFn) -> &mut Self
pub fn add_filter(&mut self, name: &str, filter: FilterFn) -> &mut Self
Registers a custom filter under name. Custom filters are
looked up before the built-in set, so registering a name
that already exists (e.g. uppercase) overrides the built-in.
Returns &mut Self for builder-style chaining.
The filter receives the current pipeline value as &str and
any colon-separated arguments as &[String]. See
FilterFn for the full signature.
§Examples
use staticweaver::{Context, Engine};
use std::sync::Arc;
use std::time::Duration;
let mut engine = Engine::new("", Duration::from_secs(60));
engine.add_filter(
"shout",
Arc::new(|input, _args| Ok(format!("{}!!!", input.to_uppercase()))),
);
let mut ctx = Context::new();
ctx.set("greeting".to_string(), "hello".to_string());
let out = engine
.render_template("{{greeting | shout}}", &ctx)
.unwrap();
assert_eq!(out, "HELLO!!!");Sourcepub fn add_test(&mut self, name: &str, test: TestFn) -> &mut Self
pub fn add_test(&mut self, name: &str, test: TestFn) -> &mut Self
Registers a custom test under name. Custom tests are
looked up before the built-in set (defined, empty,
none), so registering a name that already exists overrides
the built-in. Returns &mut Self for builder-style chaining.
Used in #if block expressions: {{#if value is X}}…{{/if}}
passes value and any colon-separated args to the test
function, which returns a boolean. is not X flips the
result via the same negation pathway that built-ins use.
§Examples
use staticweaver::{Context, Engine};
use staticweaver::context::Value;
use std::sync::Arc;
use std::time::Duration;
let mut engine = Engine::new("", Duration::from_secs(60));
engine.add_test(
"admin",
Arc::new(|v, _args| {
Ok(matches!(v, Value::String(s) if s == "admin"))
}),
);
let mut ctx = Context::new();
ctx.set("role".to_string(), "admin".to_string());
let out = engine
.render_template(
"{{#if role is admin}}Y{{else}}N{{/if}}",
&ctx,
)
.unwrap();
assert_eq!(out, "Y");Sourcepub fn with_html_escape(self, enable: bool) -> Self
pub fn with_html_escape(self, enable: bool) -> Self
Toggles HTML escaping for substituted values. Returns self for
builder-style chaining. Escaping is on by default; disable it only
when the engine is used to render non-HTML output or when the caller
escapes values themselves.
§Examples
use staticweaver::{Context, Engine};
use std::time::Duration;
let engine = Engine::new("", Duration::from_secs(60))
.with_html_escape(false);
let mut ctx = Context::new();
ctx.set("body".to_string(), "<b>hi</b>".to_string());
let out = engine.render_template("{{body}}", &ctx).unwrap();
assert_eq!(out, "<b>hi</b>");Sourcepub fn with_lax_undefined(self, lax: bool) -> Self
pub fn with_lax_undefined(self, lax: bool) -> Self
Sets whether unresolved {{key}} substitutions abort the
render (strict, default) or emit an empty string (lax).
Lax mode mirrors Jinja2’s “undefined” behaviour and lets sites whose page templates reference variables that not every page supplies build without per-page shims. Issue #28.
§Examples
use staticweaver::{Context, Engine};
use std::time::Duration;
let mut engine = Engine::new("", Duration::from_secs(60))
.with_lax_undefined(true);
let ctx = Context::new();
assert_eq!(
engine.render_template("hello {{name}}", &ctx).unwrap(),
"hello ",
);Sourcepub fn render_page(
&self,
context: &Context,
layout: &str,
) -> Result<String, EngineError>
pub fn render_page( &self, context: &Context, layout: &str, ) -> Result<String, EngineError>
Renders a full page using a layout file from the template_path.
The engine automatically appends .html to the layout name.
Results are cached using a combined hash of the layout name and
the provided context.
§Arguments
context- The data context for template substitution.layout- The name of the layout file (without.html).
§Errors
Returns EngineError::Io if the layout file cannot be read, or
EngineError::InvalidTemplate if the name is malformed (e.g.
contains .. traversal).
§Examples
use staticweaver::{Context, Engine};
use std::time::Duration;
use std::fs;
use tempfile::TempDir;
let temp = TempDir::new().unwrap();
fs::write(temp.path().join("index.html"), "Hello, {{name}}!").unwrap();
let mut engine = Engine::new(
temp.path().to_str().unwrap(),
Duration::from_secs(60),
);
let mut context = Context::new();
context.set("name".to_string(), "World".to_string());
let rendered = engine.render_page(&context, "index").unwrap();
assert_eq!(rendered, "Hello, World!");Sourcepub fn render_template(
&self,
template: &str,
context: &Context,
) -> Result<String, EngineError>
pub fn render_template( &self, template: &str, context: &Context, ) -> Result<String, EngineError>
Renders a raw template string against the provided context.
Supports:
{{ key }}: Substitution (HTML escaped by default).{{!key}}: Raw substitution (no escaping).{{> partial}}: Recursive partial inclusion.{{#if key}}...{{else}}...{{/if}}: Conditionals.{{#each list}}...{{/each}}: Iteration.
§Arguments
template- The raw string containing template tags.context- The data context.
§Errors
Returns EngineError::InvalidTemplate for syntax errors or
EngineError::Render for unresolved tags or filter errors.
§Examples
use staticweaver::{Context, Engine};
use std::time::Duration;
let engine = Engine::new("templates", Duration::from_secs(60));
let mut ctx = Context::new();
ctx.set_value("items".to_string(), vec!["a", "b"]);
let out = engine.render_template(
"{{#each items}}{{this}} {{/each}}",
&ctx
).unwrap();
assert_eq!(out, "a b ");Sourcepub fn render_to<W: Write>(
&self,
template: &str,
context: &Context,
writer: &mut W,
) -> Result<(), EngineError>
pub fn render_to<W: Write>( &self, template: &str, context: &Context, writer: &mut W, ) -> Result<(), EngineError>
Renders template against context and writes the result
directly to writer. Convenience wrapper for callers that want
to stream into a Vec<u8>, an HTTP response body, a file, or
any other std::io::Write sink without managing the
intermediate String themselves.
Equivalent to writer.write_all(engine.render_template(t, c)? .as_bytes()) with two differences: I/O failures map cleanly
to EngineError::Io, and a future zero-copy variant could
land here without changing the call site.
§Note
The implementation still allocates one String internally.
The whitespace-control trim ({{- ... -}}) needs lookback
into the rendered buffer, which io::Write cannot provide.
True zero-copy streaming would require either dropping
{{- -}} support or buffering the would-be-trimmed bytes;
neither is worth the API churn today.
§Examples
use staticweaver::{Context, Engine};
use std::time::Duration;
let engine = Engine::new("", Duration::from_secs(60));
let mut ctx = Context::new();
ctx.set("name".to_string(), "Ada".to_string());
let mut buf: Vec<u8> = Vec::new();
engine
.render_to("Hello, {{name}}!", &ctx, &mut buf)
.unwrap();
assert_eq!(buf, b"Hello, Ada!");Sourcepub fn render_page_to<W: Write>(
&self,
context: &Context,
layout: &str,
writer: &mut W,
) -> Result<(), EngineError>
pub fn render_page_to<W: Write>( &self, context: &Context, layout: &str, writer: &mut W, ) -> Result<(), EngineError>
File-backed counterpart to Engine::render_to. Looks up
layout in template_path (with .html appended), renders
the page, and writes the result to writer. Caches the
rendered output by (layout, ctx.hash()) like
Engine::render_page.
§Examples
use staticweaver::{Context, Engine};
use std::time::Duration;
use std::fs::File;
let mut engine = Engine::new("templates", Duration::from_secs(60));
let ctx = Context::new();
let mut out = File::create("/tmp/page.html").unwrap();
engine.render_page_to(&ctx, "index", &mut out).unwrap();Sourcepub fn set_delimiters(&mut self, open: &str, close: &str)
pub fn set_delimiters(&mut self, open: &str, close: &str)
Changes the delimiters used to identify template tags.
Default is {{ and }}.
§Examples
use staticweaver::{Context, Engine};
use std::time::Duration;
let mut engine = Engine::new("t", Duration::from_secs(60));
engine.set_delimiters("[[", "]]");
let mut ctx = Context::new();
ctx.set("k".to_string(), "v".to_string());
assert_eq!(engine.render_template("[[k]]", &ctx).unwrap(), "v");Sourcepub fn set_max_cache_size(&self, size: usize)
pub fn set_max_cache_size(&self, size: usize)
Limits the number of rendered pages held in the memory cache.
If the cache currently exceeds size, it will be cleared.
§Examples
use staticweaver::Engine;
use std::time::Duration;
let mut engine = Engine::new("t", Duration::from_secs(60));
engine.set_max_cache_size(10);Sourcepub fn clear_cache(&self)
pub fn clear_cache(&self)
Drops all entries from the internal rendering cache.
§Examples
use staticweaver::Engine;
use std::time::Duration;
let mut engine = Engine::new("t", Duration::from_secs(60));
engine.clear_cache();Sourcepub fn create_template_folder(
&self,
template_path: Option<&str>,
) -> Result<String, EngineError>
pub fn create_template_folder( &self, template_path: Option<&str>, ) -> Result<String, EngineError>
Prepares a local directory for template storage.
If template_path is a local directory, it returns the absolute
path if it exists. If it’s a URL, and the remote-templates
feature is enabled, the engine will attempt to fetch a standard set
of template files (DEFAULT_TEMPLATE_FILES).
§Arguments
template_path- Local path or URL source.
§Errors
EngineError::Io: the directory does not exist.EngineError::InvalidTemplate:template_pathisNone, or a URL was supplied without theremote-templatesfeature.
§Examples
use staticweaver::Engine;
use std::time::Duration;
let engine = Engine::new("templates", Duration::from_secs(60));
// `None` is rejected — callers must pass a path or URL explicitly.
assert!(engine.create_template_folder(None).is_err());Sourcepub fn create_template_folder_with_files(
&self,
template_path: Option<&str>,
files: &[&str],
) -> Result<String, EngineError>
pub fn create_template_folder_with_files( &self, template_path: Option<&str>, files: &[&str], ) -> Result<String, EngineError>
Same as create_template_folder but
accepts a caller-supplied list of filenames to download when
template_path is a URL. Useful when the default
DEFAULT_TEMPLATE_FILES set does not match the remote layout.
files is ignored for local-directory paths.
§Examples
use staticweaver::Engine;
use std::time::Duration;
let engine = Engine::new("templates", Duration::from_secs(60));
// Pass a custom filename list (e.g. just index.html).
let _ = engine.create_template_folder_with_files(Some("."), &["index.html"]);Source§impl Engine
impl Engine
Sourcepub async fn render_template_async<L>(
&self,
loader: &L,
name: &str,
context: &Context,
) -> Result<String, EngineError>where
L: AsyncTemplateLoader,
pub async fn render_template_async<L>(
&self,
loader: &L,
name: &str,
context: &Context,
) -> Result<String, EngineError>where
L: AsyncTemplateLoader,
Async counterpart to Engine::render_template: loads the
named template via loader (asynchronously), then renders
it synchronously against context. Issue #37.
The render itself is CPU-bound and stays sync — the async-ness
comes from the loader IO. If you already have the template
body in memory, prefer render_template directly.
§Examples
// Requires the `async-tokio` feature + a tokio runtime.
use staticweaver::loader_async::MemoryAsyncLoader;
use staticweaver::{Context, Engine};
use std::collections::HashMap;
use std::time::Duration;
let mut store = HashMap::new();
let _ = store.insert("hi".to_string(), "Hello {{name}}!".to_string());
let loader = MemoryAsyncLoader::new(store);
let engine = Engine::new("", Duration::from_secs(60));
let mut ctx = Context::new();
ctx.set("name".to_string(), "Ada".to_string());
let out = engine.render_template_async(&loader, "hi", &ctx).await?;
assert_eq!(out, "Hello Ada!");Sourcepub async fn render_page_async<L>(
&self,
loader: &L,
context: &Context,
layout: &str,
) -> Result<String, EngineError>where
L: AsyncTemplateLoader,
pub async fn render_page_async<L>(
&self,
loader: &L,
context: &Context,
layout: &str,
) -> Result<String, EngineError>where
L: AsyncTemplateLoader,
Async counterpart to Engine::render_page: loads the layout
via loader, applies the per-extension auto-escape policy,
renders, and memoises the result in the same Mutex-protected
render_cache the sync path uses. Issue #37.
Two concurrent async tasks calling this with the same key race the insert harmlessly — both produce identical bytes because the inputs are identical.
§Examples
// Requires the `async-tokio` feature + a tokio runtime.
use staticweaver::loader_async::MemoryAsyncLoader;
use staticweaver::{Context, Engine};
use std::collections::HashMap;
use std::time::Duration;
let mut store = HashMap::new();
let _ = store.insert("page".to_string(), "v={{v}}".to_string());
let loader = MemoryAsyncLoader::new(store);
let engine = Engine::new("", Duration::from_secs(60));
let mut ctx = Context::new();
ctx.set("v".to_string(), "ok".to_string());
let out = engine.render_page_async(&loader, &ctx, "page").await?;
assert_eq!(out, "v=ok");Sourcepub async fn render_to_async<W>(
&self,
template: &str,
context: &Context,
writer: &mut W,
) -> Result<(), EngineError>
pub async fn render_to_async<W>( &self, template: &str, context: &Context, writer: &mut W, ) -> Result<(), EngineError>
Async streaming sink — issue #38. Mirror of
Engine::render_to for AsyncWrite-flavoured destinations
(tokio::fs::File, tokio::net::TcpStream, an Axum body
channel). The render itself stays sync; the bytes flush
through the async writer.
Requires the async-tokio feature for the AsyncWriteExt
extension trait.
§Examples
// Requires the `async-tokio` feature + a tokio runtime.
use staticweaver::{Context, Engine};
use std::time::Duration;
let engine = Engine::new("", Duration::from_secs(60));
let mut ctx = Context::new();
ctx.set("who".to_string(), "world".to_string());
let mut sink: Vec<u8> = Vec::new();
engine.render_to_async("hi {{who}}", &ctx, &mut sink).await?;
assert_eq!(&sink, b"hi world");Sourcepub async fn render_page_to_async<L, W>(
&self,
loader: &L,
context: &Context,
layout: &str,
writer: &mut W,
) -> Result<(), EngineError>
pub async fn render_page_to_async<L, W>( &self, loader: &L, context: &Context, layout: &str, writer: &mut W, ) -> Result<(), EngineError>
Page-flavoured async streaming sink — issue #38. Combines
async load + sync render + async write into one call. Errors
surface as EngineError.
§Examples
// Requires the `async-tokio` feature + a tokio runtime.
use staticweaver::loader_async::MemoryAsyncLoader;
use staticweaver::{Context, Engine};
use std::collections::HashMap;
use std::time::Duration;
let mut store = HashMap::new();
let _ = store.insert("p".to_string(), "[{{a}}]".to_string());
let loader = MemoryAsyncLoader::new(store);
let engine = Engine::new("", Duration::from_secs(60));
let mut ctx = Context::new();
ctx.set("a".to_string(), "ok".to_string());
let mut sink: Vec<u8> = Vec::new();
engine.render_page_to_async(&loader, &ctx, "p", &mut sink).await?;
assert_eq!(&sink, b"[ok]");