staticweaver/engine.rs
1// Copyright © 2024 StaticWeaver. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! # Engine Module
5//!
6//! The template rendering engine. The [`Engine`] struct holds the
7//! template root directory, the render cache, and the active delimiter
8//! pair, and exposes [`Engine::render_template`] (string-in, string-out)
9//! and [`Engine::render_page`] (read a `.html` layout from disk).
10//!
11//! ## Templating language
12//!
13//! - **Substitution**: `{{key}}` looks up a `Context` value and emits
14//! it. Default behaviour HTML-escapes `& < > " '`. Use `{{!key}}` to
15//! emit the value verbatim, or
16//! [`Engine::with_html_escape(false)`](Engine::with_html_escape) to
17//! disable escape globally.
18//! - **Dot-notation**: `{{user.email}}` walks a [`Value::Map`](crate::context::Value);
19//! `{{items.0}}` indexes a [`Value::List`](crate::context::Value).
20//! - **Control flow**: `{{#if EXPR}}…{{else}}…{{/if}}` and
21//! `{{#each list}}…{{/each}}`. Each-blocks expose the loop helpers
22//! `@index`, `@first`, `@last`, and (for `Map` iteration) `@key`,
23//! binding each element to `this`.
24//! - **Expressions** (inside `#if`): comparisons (`==`, `!=`, `<`,
25//! `<=`, `>`, `>=`), short-circuiting boolean operators (`and`,
26//! `or`, `not`), checked integer math (`+`, `-`, `*`, `/`), and
27//! postfix tests (`is defined`, `is empty`, `is none`) with
28//! `is not` for negation. Precedence: postfix tests bind tightest,
29//! then math, comparisons, `not`, `and`, `or`. Bare paths like
30//! `{{#if user}}` keep their truthiness semantics.
31//! - **Partials**: `{{> name}}` reads `name.html` from
32//! `template_path` and substitutes the parent context. Pass scoped
33//! parameters via `{{> name k=v}}`. Recursion is capped at depth 10.
34//! - **Inheritance**: `{{#extends "base"}}` plus
35//! `{{#block "name"}}…{{/block}}` lets a child template override
36//! named blocks in its parent. Multi-level chains compose; the
37//! child wins on conflicting block names.
38//! - **In-template assignment**: `{{#set name = LITERAL}}` binds a
39//! value locally for subsequent tags. Local-scope only — does not
40//! leak into the parent context.
41//! - **Filters**: `{{ x | filter }}`, with arguments via
42//! `{{ x | filter:arg }}`. Built-in filters: `uppercase`,
43//! `lowercase`, `trim`, `truncate`, `capitalize`, `length`,
44//! `default`, `replace`, `urlencode`, `safe`.
45//! - **Comments**: `{{! one-line }}` and `{{!-- multi-line --}}` are
46//! stripped before rendering.
47//! - **Whitespace control**: `{{- key -}}` trims adjacent whitespace
48//! on the corresponding side of the tag.
49//! - **Backslash escape**: `\{{literal}}` emits `{{literal}}`
50//! verbatim. Even runs collapse to literal backslashes, odd runs
51//! escape the following delimiter.
52//! - **Custom delimiters**:
53//! [`Engine::set_delimiters("<<", ">>")`](Engine::set_delimiters)
54//! swaps `{{` / `}}` for any pair.
55//!
56//! ## Caching
57//!
58//! [`Engine::render_page`] caches results keyed by
59//! `"{layout}:{Context::hash()}"`. The cache uses true LRU eviction
60//! when bounded — see [`crate::cache`].
61//!
62//! ## Errors
63//!
64//! Both render entry points return `Result<String, EngineError>`.
65//! Missing keys produce `EngineError::Render`; malformed templates
66//! produce `EngineError::InvalidTemplate`. See [`crate::error`].
67//!
68//! ## Examples
69//!
70//! ```
71//! use staticweaver::{Context, Engine};
72//! use std::time::Duration;
73//!
74//! let engine = Engine::new("templates", Duration::from_secs(60));
75//! let mut ctx = Context::new();
76//! ctx.set("name".to_string(), "Ada".to_string());
77//! let out = engine
78//! .render_template("Hello, {{name}}!", &ctx)
79//! .unwrap();
80//! assert_eq!(out, "Hello, Ada!");
81//! ```
82
83use crate::cache::Cache;
84use crate::context::Context;
85use staticweaver_core::path::{resolve_template_path, validate_name};
86use staticweaver_core::Renderer;
87use std::collections::HashMap;
88use std::fs;
89use std::io::{self, Write};
90#[cfg(feature = "remote-templates")]
91use std::path::Path;
92use std::path::PathBuf;
93use std::sync::Arc;
94use std::time::Duration;
95
96/// Filter, test and loader extension points. Defined in
97/// `staticweaver-core` and re-exported here at their historical paths.
98pub use staticweaver_core::{FilterFn, TemplateLoader, TestFn};
99
100/// Filesystem-backed [`TemplateLoader`]. Resolves
101/// `name` to `<root>/<name>.html`. Used as the default loader by
102/// [`Engine::new`].
103///
104/// # Examples
105///
106/// ```
107/// use staticweaver::engine::{FsLoader, TemplateLoader};
108/// use std::path::PathBuf;
109///
110/// let loader = FsLoader::new(PathBuf::from("templates"));
111/// // loader.load("post") would read templates/post.html
112/// let _ = loader; // silence unused warning
113/// ```
114#[derive(Debug, Clone)]
115pub struct FsLoader {
116 /// Directory under which `name.html` files live.
117 ///
118 /// # Examples
119 ///
120 /// ```
121 /// use staticweaver::engine::FsLoader;
122 /// use std::path::PathBuf;
123 /// let loader = FsLoader::new(PathBuf::from("templates"));
124 /// assert_eq!(loader.root, PathBuf::from("templates"));
125 /// ```
126 pub root: PathBuf,
127}
128
129impl FsLoader {
130 /// Creates a new `FsLoader` rooted at `root`.
131 ///
132 /// # Examples
133 ///
134 /// ```
135 /// use staticweaver::engine::FsLoader;
136 /// use std::path::PathBuf;
137 /// let loader = FsLoader::new(PathBuf::from("templates"));
138 /// assert_eq!(loader.root, PathBuf::from("templates"));
139 /// ```
140 #[must_use]
141 pub fn new(root: PathBuf) -> Self {
142 Self { root }
143 }
144}
145
146impl TemplateLoader for FsLoader {
147 fn load(&self, name: &str) -> Result<String, EngineError> {
148 let path =
149 resolve_template_path(&self.root, &format!("{name}.html"))?;
150 Ok(fs::read_to_string(&path)?)
151 }
152}
153
154/// In-memory [`TemplateLoader`] backed by a `HashMap`. Useful for
155/// tests, embedded asset bundles, or any case where templates are
156/// known at build time and shouldn't touch the filesystem.
157///
158/// # Examples
159///
160/// ```
161/// use staticweaver::engine::{MemoryLoader, TemplateLoader};
162/// use std::collections::HashMap;
163///
164/// let mut map = HashMap::new();
165/// let _ = map.insert("greet".to_string(), "Hello!".to_string());
166/// let loader = MemoryLoader::new(map);
167/// assert_eq!(loader.load("greet").unwrap(), "Hello!");
168/// ```
169#[derive(Debug, Clone, Default)]
170pub struct MemoryLoader {
171 /// Template name → body map.
172 ///
173 /// # Examples
174 ///
175 /// ```
176 /// use staticweaver::engine::MemoryLoader;
177 /// let mut loader = MemoryLoader::default();
178 /// let _ = loader.insert("hello", "Hi {{name}}!");
179 /// assert_eq!(loader.templates.len(), 1);
180 /// ```
181 pub templates: HashMap<String, String>,
182}
183
184impl MemoryLoader {
185 /// Creates a `MemoryLoader` populated with `templates`.
186 ///
187 /// # Examples
188 ///
189 /// ```
190 /// use staticweaver::engine::MemoryLoader;
191 /// use std::collections::HashMap;
192 /// let mut store = HashMap::new();
193 /// let _ = store.insert("k".to_string(), "v".to_string());
194 /// let loader = MemoryLoader::new(store);
195 /// assert_eq!(loader.templates.len(), 1);
196 /// ```
197 #[must_use]
198 pub fn new(templates: HashMap<String, String>) -> Self {
199 Self { templates }
200 }
201
202 /// Inserts or replaces the template named `name`. Returns the
203 /// previous body if any.
204 ///
205 /// # Examples
206 ///
207 /// ```
208 /// use staticweaver::engine::MemoryLoader;
209 /// let mut loader = MemoryLoader::default();
210 /// assert_eq!(loader.insert("k", "first"), None);
211 /// assert_eq!(loader.insert("k", "second").as_deref(), Some("first"));
212 /// ```
213 pub fn insert(
214 &mut self,
215 name: impl Into<String>,
216 body: impl Into<String>,
217 ) -> Option<String> {
218 self.templates.insert(name.into(), body.into())
219 }
220}
221
222impl TemplateLoader for MemoryLoader {
223 fn load(&self, name: &str) -> Result<String, EngineError> {
224 self.templates.get(name).cloned().ok_or_else(|| {
225 EngineError::Io(io::Error::new(
226 io::ErrorKind::NotFound,
227 format!("MemoryLoader: no template named `{name}`"),
228 ))
229 })
230 }
231}
232
233#[cfg(feature = "remote-templates")]
234use std::fs::File;
235
236/// Canonical engine error type. Re-exported from `crate::error` to keep a
237/// single source of truth; callers can use either `staticweaver::EngineError`
238/// or `staticweaver::engine::EngineError` and pattern-match interchangeably.
239///
240/// # Examples
241///
242/// ```
243/// // Both paths refer to the same type.
244/// fn _f(e: staticweaver::engine::EngineError)
245/// -> staticweaver::EngineError { e }
246/// ```
247pub use crate::error::EngineError;
248
249/// Filenames fetched by default when `Engine::create_template_folder` is
250/// called with an HTTP/S URL and no explicit file list. Matches the
251/// historical six-file set for backwards compatibility; callers who need
252/// a different layout should use
253/// [`Engine::create_template_folder_with_files`].
254///
255/// # Examples
256///
257/// ```
258/// use staticweaver::engine::DEFAULT_TEMPLATE_FILES;
259/// assert!(DEFAULT_TEMPLATE_FILES.contains(&"index.html"));
260/// ```
261pub const DEFAULT_TEMPLATE_FILES: &[&str] = &[
262 "contact.html",
263 "index.html",
264 "page.html",
265 "post.html",
266 "main.js",
267 "sw.js",
268];
269
270/// The main template rendering engine.
271///
272/// # Examples
273///
274/// ```
275/// use staticweaver::{Context, Engine};
276/// use std::time::Duration;
277///
278/// let engine = Engine::new("templates", Duration::from_secs(60));
279/// let mut ctx = Context::new();
280/// ctx.set("who".to_string(), "world".to_string());
281/// let out = engine.render_template("hello {{who}}", &ctx).unwrap();
282/// assert_eq!(out, "hello world");
283/// ```
284pub struct Engine {
285 /// Path to the template directory.
286 ///
287 /// # Examples
288 ///
289 /// ```
290 /// use staticweaver::Engine;
291 /// use std::time::Duration;
292 /// let engine = Engine::new("templates", Duration::from_secs(60));
293 /// assert_eq!(engine.template_path, "templates");
294 /// ```
295 pub template_path: String,
296 /// Cache for rendered templates keyed by `"{layout}:{ctx.hash()}"`.
297 ///
298 /// Wrapped in `Mutex` (issue #36, v0.0.4) so `Engine` is `Send + Sync`
299 /// and `render_page` can take `&self` — making the engine sharable
300 /// across threads / async tasks via `Arc<Engine>` without the
301 /// `Arc<Mutex<Engine>>` envelope users previously had to write.
302 /// The lock is held only across the cache lookup or insert; the
303 /// expensive render work happens outside it.
304 ///
305 /// # Examples
306 ///
307 /// ```
308 /// use staticweaver::Engine;
309 /// use std::time::Duration;
310 /// let engine = Engine::new("", Duration::from_secs(60));
311 /// assert_eq!(engine.render_cache.lock().unwrap().len(), 0);
312 /// ```
313 pub render_cache: std::sync::Mutex<Cache<String, String>>,
314 /// Opening delimiter for template tags. Defaults to `"{{"`.
315 ///
316 /// # Examples
317 ///
318 /// ```
319 /// use staticweaver::Engine;
320 /// use std::time::Duration;
321 /// let engine = Engine::new("", Duration::from_secs(60));
322 /// assert_eq!(engine.open_delim, "{{");
323 /// ```
324 pub open_delim: String,
325 /// Closing delimiter for template tags. Defaults to `"}}"`.
326 ///
327 /// # Examples
328 ///
329 /// ```
330 /// use staticweaver::Engine;
331 /// use std::time::Duration;
332 /// let engine = Engine::new("", Duration::from_secs(60));
333 /// assert_eq!(engine.close_delim, "}}");
334 /// ```
335 pub close_delim: String,
336 /// When true, values substituted into templates are HTML-escaped
337 /// (`&`, `<`, `>`, `"`, `'`). Prefix a key with `!` to opt out per-tag
338 /// (e.g. `{{!content}}` emits the raw value).
339 ///
340 /// # Examples
341 ///
342 /// ```
343 /// use staticweaver::Engine;
344 /// use std::time::Duration;
345 /// let engine = Engine::new("", Duration::from_secs(60))
346 /// .with_html_escape(false);
347 /// assert!(!engine.escape_html);
348 /// ```
349 pub escape_html: bool,
350 /// User-registered filters keyed by name. Looked up *before* the
351 /// built-in filter set, so a custom filter can override a
352 /// built-in of the same name. Populate via [`Engine::add_filter`].
353 ///
354 /// # Examples
355 ///
356 /// ```
357 /// use staticweaver::Engine;
358 /// use std::sync::Arc;
359 /// use std::time::Duration;
360 /// let mut engine = Engine::new("", Duration::from_secs(60));
361 /// let _ = engine.add_filter(
362 /// "shout",
363 /// Arc::new(|s, _| Ok(s.to_uppercase())),
364 /// );
365 /// assert!(engine.custom_filters.contains_key("shout"));
366 /// ```
367 pub custom_filters: HashMap<String, FilterFn>,
368 /// User-registered tests keyed by name. Looked up *before* the
369 /// built-in tests (`defined`, `empty`, `none`) so a custom test
370 /// can override a built-in of the same name. Populate via
371 /// [`Engine::add_test`].
372 ///
373 /// # Examples
374 ///
375 /// ```
376 /// use staticweaver::Engine;
377 /// use std::sync::Arc;
378 /// use std::time::Duration;
379 /// let mut engine = Engine::new("", Duration::from_secs(60));
380 /// let _ = engine.add_test("admin", Arc::new(|_v, _| Ok(true)));
381 /// assert!(engine.custom_tests.contains_key("admin"));
382 /// ```
383 pub custom_tests: HashMap<String, TestFn>,
384 /// Source of template content for `render_page`, partial
385 /// includes, and `{{#extends}}`. Defaults to an [`FsLoader`]
386 /// rooted at `template_path`. Override via
387 /// [`Engine::with_loader`] for in-memory or custom-backend
388 /// templates.
389 ///
390 /// # Examples
391 ///
392 /// ```
393 /// use staticweaver::Engine;
394 /// use std::time::Duration;
395 /// let engine = Engine::new("templates", Duration::from_secs(60));
396 /// // The default loader is an FsLoader; the field exposes it
397 /// // as a trait object so callers can swap it freely.
398 /// assert!(engine.loader.load("missing").is_err());
399 /// ```
400 pub loader: Arc<dyn TemplateLoader>,
401 /// File extensions (e.g. `.html`, `.xml`) for which
402 /// [`Engine::render_page`] auto-escapes substitutions.
403 /// Empty (default) = use the global `escape_html` setting
404 /// uniformly. When non-empty, layouts whose name ends with one
405 /// of these extensions auto-escape; everything else renders
406 /// raw. Matches Tera's per-extension autoescape behaviour.
407 /// Populate via [`Engine::autoescape_on`].
408 ///
409 /// # Examples
410 ///
411 /// ```
412 /// use staticweaver::Engine;
413 /// use std::time::Duration;
414 /// let mut engine = Engine::new("", Duration::from_secs(60));
415 /// let _ = engine.autoescape_on(&[".html"]);
416 /// assert_eq!(engine.autoescape_extensions, vec![".html"]);
417 /// ```
418 pub autoescape_extensions: Vec<String>,
419 /// When `true`, an unresolved `{{key}}` substitution emits an
420 /// empty string instead of aborting the render with
421 /// `EngineError::Render("Unresolved template tag: <key>")`.
422 /// Defaults to `false` (strict). Mirrors Jinja2's "undefined"
423 /// mode and lets sites whose page templates reference variables
424 /// that not every page supplies build without per-page shims.
425 /// Toggle via [`Engine::with_lax_undefined`]. Issue #28.
426 pub lax_undefined: bool,
427}
428
429// `Engine` is mostly auto-debuggable, but `custom_filters` carries
430// `Box<dyn Fn>`-style values that are not. Print only the registered
431// filter names so the rest of the struct still surfaces useful state.
432impl std::fmt::Debug for Engine {
433 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
434 f.debug_struct("Engine")
435 .field("template_path", &self.template_path)
436 .field("render_cache", &self.render_cache)
437 .field("open_delim", &self.open_delim)
438 .field("close_delim", &self.close_delim)
439 .field("escape_html", &self.escape_html)
440 .field(
441 "custom_filters",
442 &self.custom_filters.keys().collect::<Vec<_>>(),
443 )
444 .field(
445 "custom_tests",
446 &self.custom_tests.keys().collect::<Vec<_>>(),
447 )
448 // dyn-trait field — Debug just shows the placeholder.
449 .field("loader", &"<dyn TemplateLoader>")
450 .field("autoescape_extensions", &self.autoescape_extensions)
451 .field("lax_undefined", &self.lax_undefined)
452 .finish()
453 }
454}
455
456impl Engine {
457 /// Creates a new `Engine` instance with HTML escaping enabled.
458 ///
459 /// # Arguments
460 ///
461 /// * `template_path` - The path to the template directory.
462 /// * `cache_ttl` - Time-to-live for cached rendered templates.
463 ///
464 /// # Examples
465 ///
466 /// ```
467 /// use staticweaver::engine::Engine;
468 /// use std::time::Duration;
469 ///
470 /// let engine = Engine::new("templates", Duration::from_secs(3600));
471 /// ```
472 #[must_use]
473 pub fn new(template_path: &str, cache_ttl: Duration) -> Self {
474 Self {
475 template_path: template_path.to_string(),
476 render_cache: std::sync::Mutex::new(Cache::new(cache_ttl)),
477 open_delim: "{{".to_string(),
478 close_delim: "}}".to_string(),
479 escape_html: true,
480 custom_filters: HashMap::new(),
481 custom_tests: HashMap::new(),
482 loader: Arc::new(FsLoader::new(PathBuf::from(
483 template_path,
484 ))),
485 autoescape_extensions: Vec::new(),
486 lax_undefined: false,
487 }
488 }
489
490 /// Constructs an engine that loads templates through `loader`
491 /// instead of the default filesystem backend. Use this when
492 /// you want in-memory templates ([`MemoryLoader`]), templates
493 /// stored in a database, embedded asset bundles, or any other
494 /// custom source.
495 ///
496 /// `template_path` is set to the empty string in this
497 /// constructor — it's only used by the default `FsLoader`,
498 /// which the custom loader replaces. Path-validation logic on
499 /// partial / extends names still applies.
500 ///
501 /// # Examples
502 ///
503 /// ```
504 /// use staticweaver::engine::{Engine, MemoryLoader};
505 /// use staticweaver::Context;
506 /// use std::collections::HashMap;
507 /// use std::sync::Arc;
508 /// use std::time::Duration;
509 ///
510 /// let mut store = HashMap::new();
511 /// let _ = store
512 /// .insert("hello".to_string(), "Hi, {{name}}!".to_string());
513 /// let mut engine = Engine::with_loader(
514 /// Arc::new(MemoryLoader::new(store)),
515 /// Duration::from_secs(60),
516 /// );
517 ///
518 /// let mut ctx = Context::new();
519 /// ctx.set("name".to_string(), "Ada".to_string());
520 /// assert_eq!(
521 /// engine.render_page(&ctx, "hello").unwrap(),
522 /// "Hi, Ada!",
523 /// );
524 /// ```
525 #[must_use]
526 pub fn with_loader(
527 loader: Arc<dyn TemplateLoader>,
528 cache_ttl: Duration,
529 ) -> Self {
530 Self {
531 template_path: String::new(),
532 render_cache: std::sync::Mutex::new(Cache::new(cache_ttl)),
533 open_delim: "{{".to_string(),
534 close_delim: "}}".to_string(),
535 escape_html: true,
536 custom_filters: HashMap::new(),
537 custom_tests: HashMap::new(),
538 loader,
539 autoescape_extensions: Vec::new(),
540 lax_undefined: false,
541 }
542 }
543
544 /// Configures per-extension auto-escape policy for
545 /// [`Engine::render_page`]. When called with a non-empty list,
546 /// `render_page` auto-escapes ONLY for layouts whose name ends
547 /// with one of the listed suffixes; layouts with any other
548 /// extension render raw.
549 ///
550 /// Mirrors Tera's `autoescape_on(vec![".html"])`. The global
551 /// `escape_html` flag still applies to `render_template`
552 /// (which has no layout name to inspect).
553 ///
554 /// Returns `&mut Self` for builder-style chaining.
555 ///
556 /// # Examples
557 ///
558 /// ```
559 /// use staticweaver::{Context, Engine};
560 /// use staticweaver::engine::MemoryLoader;
561 /// use std::collections::HashMap;
562 /// use std::sync::Arc;
563 /// use std::time::Duration;
564 ///
565 /// let mut store = HashMap::new();
566 /// let _ = store.insert("page.html".to_string(), "{{x}}".to_string());
567 /// let _ = store.insert("plain.txt".to_string(), "{{x}}".to_string());
568 /// let mut engine = Engine::with_loader(
569 /// Arc::new(MemoryLoader::new(store)),
570 /// Duration::from_secs(60),
571 /// );
572 /// engine.autoescape_on(&[".html"]);
573 /// let mut ctx = Context::new();
574 /// ctx.set("x".to_string(), "<b>".to_string());
575 /// // .html: escaped
576 /// assert_eq!(engine.render_page(&ctx, "page.html").unwrap(), "<b>");
577 /// // .txt: raw
578 /// assert_eq!(engine.render_page(&ctx, "plain.txt").unwrap(), "<b>");
579 /// ```
580 pub fn autoescape_on(&mut self, extensions: &[&str]) -> &mut Self {
581 self.autoescape_extensions =
582 extensions.iter().map(|s| (*s).to_string()).collect();
583 self
584 }
585
586 /// Registers a custom filter under `name`. Custom filters are
587 /// looked up *before* the built-in set, so registering a name
588 /// that already exists (e.g. `uppercase`) overrides the built-in.
589 /// Returns `&mut Self` for builder-style chaining.
590 ///
591 /// The filter receives the current pipeline value as `&str` and
592 /// any colon-separated arguments as `&[String]`. See
593 /// [`FilterFn`] for the full signature.
594 ///
595 /// # Examples
596 ///
597 /// ```
598 /// use staticweaver::{Context, Engine};
599 /// use std::sync::Arc;
600 /// use std::time::Duration;
601 ///
602 /// let mut engine = Engine::new("", Duration::from_secs(60));
603 /// engine.add_filter(
604 /// "shout",
605 /// Arc::new(|input, _args| Ok(format!("{}!!!", input.to_uppercase()))),
606 /// );
607 /// let mut ctx = Context::new();
608 /// ctx.set("greeting".to_string(), "hello".to_string());
609 /// let out = engine
610 /// .render_template("{{greeting | shout}}", &ctx)
611 /// .unwrap();
612 /// assert_eq!(out, "HELLO!!!");
613 /// ```
614 pub fn add_filter(
615 &mut self,
616 name: &str,
617 filter: FilterFn,
618 ) -> &mut Self {
619 let _ = self.custom_filters.insert(name.to_string(), filter);
620 self
621 }
622
623 /// Registers a custom test under `name`. Custom tests are
624 /// looked up *before* the built-in set (`defined`, `empty`,
625 /// `none`), so registering a name that already exists overrides
626 /// the built-in. Returns `&mut Self` for builder-style chaining.
627 ///
628 /// Used in `#if` block expressions: `{{#if value is X}}…{{/if}}`
629 /// passes `value` and any colon-separated args to the test
630 /// function, which returns a boolean. `is not X` flips the
631 /// result via the same negation pathway that built-ins use.
632 ///
633 /// # Examples
634 ///
635 /// ```
636 /// use staticweaver::{Context, Engine};
637 /// use staticweaver::context::Value;
638 /// use std::sync::Arc;
639 /// use std::time::Duration;
640 ///
641 /// let mut engine = Engine::new("", Duration::from_secs(60));
642 /// engine.add_test(
643 /// "admin",
644 /// Arc::new(|v, _args| {
645 /// Ok(matches!(v, Value::String(s) if s == "admin"))
646 /// }),
647 /// );
648 /// let mut ctx = Context::new();
649 /// ctx.set("role".to_string(), "admin".to_string());
650 /// let out = engine
651 /// .render_template(
652 /// "{{#if role is admin}}Y{{else}}N{{/if}}",
653 /// &ctx,
654 /// )
655 /// .unwrap();
656 /// assert_eq!(out, "Y");
657 /// ```
658 pub fn add_test(&mut self, name: &str, test: TestFn) -> &mut Self {
659 let _ = self.custom_tests.insert(name.to_string(), test);
660 self
661 }
662
663 /// Toggles HTML escaping for substituted values. Returns `self` for
664 /// builder-style chaining. Escaping is on by default; disable it only
665 /// when the engine is used to render non-HTML output or when the caller
666 /// escapes values themselves.
667 ///
668 /// # Examples
669 ///
670 /// ```
671 /// use staticweaver::{Context, Engine};
672 /// use std::time::Duration;
673 ///
674 /// let engine = Engine::new("", Duration::from_secs(60))
675 /// .with_html_escape(false);
676 /// let mut ctx = Context::new();
677 /// ctx.set("body".to_string(), "<b>hi</b>".to_string());
678 /// let out = engine.render_template("{{body}}", &ctx).unwrap();
679 /// assert_eq!(out, "<b>hi</b>");
680 /// ```
681 #[must_use]
682 pub fn with_html_escape(mut self, enable: bool) -> Self {
683 self.escape_html = enable;
684 self
685 }
686
687 /// Sets whether unresolved `{{key}}` substitutions abort the
688 /// render (strict, default) or emit an empty string (lax).
689 ///
690 /// Lax mode mirrors Jinja2's "undefined" behaviour and lets
691 /// sites whose page templates reference variables that not every
692 /// page supplies build without per-page shims. Issue #28.
693 ///
694 /// # Examples
695 ///
696 /// ```
697 /// use staticweaver::{Context, Engine};
698 /// use std::time::Duration;
699 /// let mut engine = Engine::new("", Duration::from_secs(60))
700 /// .with_lax_undefined(true);
701 /// let ctx = Context::new();
702 /// assert_eq!(
703 /// engine.render_template("hello {{name}}", &ctx).unwrap(),
704 /// "hello ",
705 /// );
706 /// ```
707 #[must_use]
708 pub fn with_lax_undefined(mut self, lax: bool) -> Self {
709 self.lax_undefined = lax;
710 self
711 }
712
713 /// Renders a full page using a layout file from the `template_path`.
714 ///
715 /// The engine automatically appends `.html` to the `layout` name.
716 /// Results are cached using a combined hash of the layout name and
717 /// the provided `context`.
718 ///
719 /// # Arguments
720 ///
721 /// * `context` - The data context for template substitution.
722 /// * `layout` - The name of the layout file (without `.html`).
723 ///
724 /// # Errors
725 ///
726 /// Returns `EngineError::Io` if the layout file cannot be read, or
727 /// `EngineError::InvalidTemplate` if the name is malformed (e.g.
728 /// contains `..` traversal).
729 ///
730 /// # Examples
731 ///
732 /// ```
733 /// use staticweaver::{Context, Engine};
734 /// use std::time::Duration;
735 /// use std::fs;
736 /// use tempfile::TempDir;
737 ///
738 /// let temp = TempDir::new().unwrap();
739 /// fs::write(temp.path().join("index.html"), "Hello, {{name}}!").unwrap();
740 ///
741 /// let mut engine = Engine::new(
742 /// temp.path().to_str().unwrap(),
743 /// Duration::from_secs(60),
744 /// );
745 /// let mut context = Context::new();
746 /// context.set("name".to_string(), "World".to_string());
747 ///
748 /// let rendered = engine.render_page(&context, "index").unwrap();
749 /// assert_eq!(rendered, "Hello, World!");
750 /// ```
751 #[cfg_attr(
752 feature = "tracing",
753 tracing::instrument(
754 level = "debug",
755 name = "staticweaver.render_page",
756 skip(self, context),
757 fields(layout = %layout, context.len = context.len()),
758 )
759 )]
760 pub fn render_page(
761 &self,
762 context: &Context,
763 layout: &str,
764 ) -> Result<String, EngineError> {
765 // Reject any layout name that could escape the template directory.
766 // Callers pass values like "post", "default", or "blog/post".
767 validate_name(layout)?;
768
769 let cache_key = format!("{}:{}", layout, context.hash());
770
771 // Return cached result if available. The Mutex (issue #36)
772 // is held only across the lookup — the expensive render work
773 // below happens outside it, so concurrent render_page calls
774 // for *different* keys parallelise.
775 if let Some(cached) = self
776 .render_cache
777 .lock()
778 .expect("cache poisoned")
779 .get(&cache_key)
780 {
781 return Ok(cached.to_string());
782 }
783
784 // Load the layout body via the configured TemplateLoader
785 // (defaults to FsLoader rooted at `self.template_path`).
786 let template_content = self.loader.load(layout)?;
787
788 // Render the template with the provided context, under the
789 // layout's per-extension escape policy.
790 let output = self
791 .renderer(self.effective_escape(layout))
792 .render(&template_content, context)?;
793
794 // Cache the rendered result for future use. Lock-and-insert
795 // is a separate critical section from the lookup above — a
796 // concurrent insert for the same key races but is harmless
797 // (last-writer wins; both renders produce the same bytes
798 // because the inputs are identical).
799 let _ = self
800 .render_cache
801 .lock()
802 .expect("cache poisoned")
803 .insert(cache_key, output.clone());
804
805 Ok(output)
806 }
807
808 /// Renders a raw template string against the provided `context`.
809 ///
810 /// Supports:
811 /// - `{{ key }}`: Substitution (HTML escaped by default).
812 /// - `{{!key}}`: Raw substitution (no escaping).
813 /// - `{{> partial}}`: Recursive partial inclusion.
814 /// - `{{#if key}}...{{else}}...{{/if}}`: Conditionals.
815 /// - `{{#each list}}...{{/each}}`: Iteration.
816 ///
817 /// # Arguments
818 ///
819 /// * `template` - The raw string containing template tags.
820 /// * `context` - The data context.
821 ///
822 /// # Errors
823 ///
824 /// Returns `EngineError::InvalidTemplate` for syntax errors or
825 /// `EngineError::Render` for unresolved tags or filter errors.
826 ///
827 /// # Examples
828 ///
829 /// ```
830 /// use staticweaver::{Context, Engine};
831 /// use std::time::Duration;
832 ///
833 /// let engine = Engine::new("templates", Duration::from_secs(60));
834 /// let mut ctx = Context::new();
835 /// ctx.set_value("items".to_string(), vec!["a", "b"]);
836 ///
837 /// let out = engine.render_template(
838 /// "{{#each items}}{{this}} {{/each}}",
839 /// &ctx
840 /// ).unwrap();
841 /// assert_eq!(out, "a b ");
842 /// ```
843 #[cfg_attr(
844 feature = "tracing",
845 tracing::instrument(
846 level = "debug",
847 name = "staticweaver.render_template",
848 skip(self, context),
849 fields(template.bytes = template.len()),
850 )
851 )]
852 pub fn render_template(
853 &self,
854 template: &str,
855 context: &Context,
856 ) -> Result<String, EngineError> {
857 if template.trim().is_empty() {
858 return Err(EngineError::InvalidTemplate(
859 "Template is empty".to_string(),
860 ));
861 }
862
863 self.renderer(self.escape_html).render(template, context)
864 }
865
866 /// Per-extension auto-escape policy: if the user opted in via
867 /// `autoescape_on(&[".html", …])`, the layout's own extension
868 /// decides whether substitutions get escaped, not the global
869 /// `escape_html` flag. Computed per call and passed down, with no
870 /// mutation of `self.escape_html` (which would make render_page
871 /// require `&mut self` and race across concurrent renders).
872 fn effective_escape(&self, layout: &str) -> bool {
873 if self.autoescape_extensions.is_empty() {
874 self.escape_html
875 } else {
876 self.autoescape_extensions
877 .iter()
878 .any(|ext| layout.ends_with(ext.as_str()))
879 }
880 }
881
882 /// Borrows this engine's configuration as a core
883 /// [`Renderer`](staticweaver_core::Renderer).
884 fn renderer(&self, escape_html: bool) -> Renderer<'_> {
885 Renderer::new(&*self.loader)
886 .delimiters(&self.open_delim, &self.close_delim)
887 .escape_html(escape_html)
888 .lax_undefined(self.lax_undefined)
889 .filters(&self.custom_filters)
890 .tests(&self.custom_tests)
891 }
892
893 /// Renders `template` against `context` and writes the result
894 /// directly to `writer`. Convenience wrapper for callers that want
895 /// to stream into a `Vec<u8>`, an HTTP response body, a file, or
896 /// any other [`std::io::Write`] sink without managing the
897 /// intermediate `String` themselves.
898 ///
899 /// Equivalent to `writer.write_all(engine.render_template(t, c)?
900 /// .as_bytes())` with two differences: I/O failures map cleanly
901 /// to `EngineError::Io`, and a future zero-copy variant could
902 /// land here without changing the call site.
903 ///
904 /// # Note
905 ///
906 /// The implementation still allocates one `String` internally.
907 /// The whitespace-control trim (`{{- ... -}}`) needs lookback
908 /// into the rendered buffer, which `io::Write` cannot provide.
909 /// True zero-copy streaming would require either dropping
910 /// `{{- -}}` support or buffering the would-be-trimmed bytes;
911 /// neither is worth the API churn today.
912 ///
913 /// # Examples
914 ///
915 /// ```
916 /// use staticweaver::{Context, Engine};
917 /// use std::time::Duration;
918 ///
919 /// let engine = Engine::new("", Duration::from_secs(60));
920 /// let mut ctx = Context::new();
921 /// ctx.set("name".to_string(), "Ada".to_string());
922 ///
923 /// let mut buf: Vec<u8> = Vec::new();
924 /// engine
925 /// .render_to("Hello, {{name}}!", &ctx, &mut buf)
926 /// .unwrap();
927 /// assert_eq!(buf, b"Hello, Ada!");
928 /// ```
929 pub fn render_to<W: Write>(
930 &self,
931 template: &str,
932 context: &Context,
933 writer: &mut W,
934 ) -> Result<(), EngineError> {
935 let rendered = self.render_template(template, context)?;
936 writer.write_all(rendered.as_bytes())?;
937 Ok(())
938 }
939
940 /// File-backed counterpart to [`Engine::render_to`]. Looks up
941 /// `layout` in `template_path` (with `.html` appended), renders
942 /// the page, and writes the result to `writer`. Caches the
943 /// rendered output by `(layout, ctx.hash())` like
944 /// [`Engine::render_page`].
945 ///
946 /// # Examples
947 ///
948 /// ```no_run
949 /// use staticweaver::{Context, Engine};
950 /// use std::time::Duration;
951 /// use std::fs::File;
952 ///
953 /// let mut engine = Engine::new("templates", Duration::from_secs(60));
954 /// let ctx = Context::new();
955 ///
956 /// let mut out = File::create("/tmp/page.html").unwrap();
957 /// engine.render_page_to(&ctx, "index", &mut out).unwrap();
958 /// ```
959 pub fn render_page_to<W: Write>(
960 &self,
961 context: &Context,
962 layout: &str,
963 writer: &mut W,
964 ) -> Result<(), EngineError> {
965 let rendered = self.render_page(context, layout)?;
966 writer.write_all(rendered.as_bytes())?;
967 Ok(())
968 }
969
970 /// Changes the delimiters used to identify template tags.
971 ///
972 /// Default is `{{` and `}}`.
973 ///
974 /// # Examples
975 ///
976 /// ```
977 /// use staticweaver::{Context, Engine};
978 /// use std::time::Duration;
979 ///
980 /// let mut engine = Engine::new("t", Duration::from_secs(60));
981 /// engine.set_delimiters("[[", "]]");
982 ///
983 /// let mut ctx = Context::new();
984 /// ctx.set("k".to_string(), "v".to_string());
985 /// assert_eq!(engine.render_template("[[k]]", &ctx).unwrap(), "v");
986 /// ```
987 pub fn set_delimiters(&mut self, open: &str, close: &str) {
988 self.open_delim = open.to_string();
989 self.close_delim = close.to_string();
990 }
991
992 /// Limits the number of rendered pages held in the memory cache.
993 ///
994 /// If the cache currently exceeds `size`, it will be cleared.
995 ///
996 /// # Examples
997 ///
998 /// ```
999 /// use staticweaver::Engine;
1000 /// use std::time::Duration;
1001 ///
1002 /// let mut engine = Engine::new("t", Duration::from_secs(60));
1003 /// engine.set_max_cache_size(10);
1004 /// ```
1005 pub fn set_max_cache_size(&self, size: usize) {
1006 self.render_cache
1007 .lock()
1008 .expect("cache poisoned")
1009 .set_capacity(size);
1010 }
1011
1012 /// Drops all entries from the internal rendering cache.
1013 ///
1014 /// # Examples
1015 ///
1016 /// ```
1017 /// use staticweaver::Engine;
1018 /// use std::time::Duration;
1019 ///
1020 /// let mut engine = Engine::new("t", Duration::from_secs(60));
1021 /// engine.clear_cache();
1022 /// ```
1023 pub fn clear_cache(&self) {
1024 self.render_cache.lock().expect("cache poisoned").clear();
1025 }
1026
1027 /// Prepares a local directory for template storage.
1028 ///
1029 /// If `template_path` is a local directory, it returns the absolute
1030 /// path if it exists. If it's a URL, and the `remote-templates`
1031 /// feature is enabled, the engine will attempt to fetch a standard set
1032 /// of template files ([`DEFAULT_TEMPLATE_FILES`]).
1033 ///
1034 /// # Arguments
1035 ///
1036 /// * `template_path` - Local path or URL source.
1037 ///
1038 /// # Errors
1039 ///
1040 /// - `EngineError::Io`: the directory does not exist.
1041 /// - `EngineError::InvalidTemplate`: `template_path` is `None`, or a URL
1042 /// was supplied without the `remote-templates` feature.
1043 ///
1044 /// # Examples
1045 ///
1046 /// ```
1047 /// use staticweaver::Engine;
1048 /// use std::time::Duration;
1049 ///
1050 /// let engine = Engine::new("templates", Duration::from_secs(60));
1051 /// // `None` is rejected — callers must pass a path or URL explicitly.
1052 /// assert!(engine.create_template_folder(None).is_err());
1053 /// ```
1054 pub fn create_template_folder(
1055 &self,
1056 template_path: Option<&str>,
1057 ) -> Result<String, EngineError> {
1058 self.create_template_folder_with_files(
1059 template_path,
1060 DEFAULT_TEMPLATE_FILES,
1061 )
1062 }
1063
1064 /// Same as [`create_template_folder`](Self::create_template_folder) but
1065 /// accepts a caller-supplied list of filenames to download when
1066 /// `template_path` is a URL. Useful when the default
1067 /// [`DEFAULT_TEMPLATE_FILES`] set does not match the remote layout.
1068 ///
1069 /// `files` is ignored for local-directory paths.
1070 ///
1071 /// # Examples
1072 ///
1073 /// ```
1074 /// use staticweaver::Engine;
1075 /// use std::time::Duration;
1076 ///
1077 /// let engine = Engine::new("templates", Duration::from_secs(60));
1078 /// // Pass a custom filename list (e.g. just index.html).
1079 /// let _ = engine.create_template_folder_with_files(Some("."), &["index.html"]);
1080 /// ```
1081 pub fn create_template_folder_with_files(
1082 &self,
1083 template_path: Option<&str>,
1084 files: &[&str],
1085 ) -> Result<String, EngineError> {
1086 let path = template_path.ok_or_else(|| {
1087 EngineError::InvalidTemplate(
1088 "template_path is required; pass a local directory or URL"
1089 .to_string(),
1090 )
1091 })?;
1092
1093 if is_url(path) {
1094 #[cfg(feature = "remote-templates")]
1095 {
1096 if files.is_empty() {
1097 return Err(EngineError::InvalidTemplate(
1098 "files list must not be empty for URL fetches"
1099 .to_string(),
1100 ));
1101 }
1102 crate::transport::require_permitted(path)?;
1103 let dir = Self::download_files_from_url(path, files)?;
1104 return dir.to_str().map(str::to_string).ok_or_else(
1105 || {
1106 EngineError::Io(io::Error::new(
1107 io::ErrorKind::InvalidData,
1108 "Invalid UTF-8 sequence in template path",
1109 ))
1110 },
1111 );
1112 }
1113 #[cfg(not(feature = "remote-templates"))]
1114 {
1115 let _ = files; // Silence unused-arg warning.
1116 return Err(EngineError::InvalidTemplate(
1117 "remote template URLs require the `remote-templates` feature"
1118 .to_string(),
1119 ));
1120 }
1121 }
1122
1123 let _ = files;
1124 let current_dir = std::env::current_dir()?;
1125 let local_path = current_dir.join(path);
1126 if local_path.exists() && local_path.is_dir() {
1127 local_path.to_str().map(str::to_string).ok_or_else(|| {
1128 EngineError::Io(io::Error::new(
1129 io::ErrorKind::InvalidData,
1130 "Invalid UTF-8 sequence in template path",
1131 ))
1132 })
1133 } else {
1134 Err(EngineError::Io(io::Error::new(
1135 io::ErrorKind::NotFound,
1136 format!("Template directory not found: {path}"),
1137 )))
1138 }
1139 }
1140
1141 /// Downloads each filename in `files` from `url` into a fresh
1142 /// temporary directory and returns its path. The temp directory is
1143 /// owned by the caller via `TempDir` and will be cleaned up on drop.
1144 #[cfg(feature = "remote-templates")]
1145 #[cfg_attr(docsrs, doc(cfg(feature = "remote-templates")))]
1146 fn download_files_from_url(
1147 url: &str,
1148 files: &[&str],
1149 ) -> Result<PathBuf, EngineError> {
1150 let dir = tempfile::tempdir()?;
1151 // `keep` (stable replacement for the deprecated `into_path`) returns
1152 // a PathBuf and suppresses cleanup; we accept that here because the
1153 // caller treats the downloaded template dir as long-lived.
1154 let template_dir_path = dir.keep();
1155
1156 for file in files {
1157 Self::download_file(url, file, &template_dir_path)?;
1158 }
1159
1160 Ok(template_dir_path)
1161 }
1162
1163 /// Downloads a single file from `url/file` into `dir`, with a 10s
1164 /// timeout, an HTTP status check, and a 1 MiB body cap so a hostile or
1165 /// misconfigured server cannot exhaust memory.
1166 #[cfg(feature = "remote-templates")]
1167 #[cfg_attr(docsrs, doc(cfg(feature = "remote-templates")))]
1168 fn download_file(
1169 url: &str,
1170 file: &str,
1171 dir: &Path,
1172 ) -> Result<(), EngineError> {
1173 /// Per-file body cap. Template assets are HTML/JS/CSS; a megabyte is
1174 /// far above any realistic payload.
1175 const MAX_BYTES: usize = 1024 * 1024;
1176
1177 let file_url = format!("{url}/{file}");
1178 let file_path = dir.join(file);
1179
1180 let client = reqwest::blocking::Client::builder()
1181 .redirect(crate::transport::redirect_policy())
1182 .build()?;
1183 let response = client
1184 .get(&file_url)
1185 .timeout(Duration::from_secs(10))
1186 .send()?;
1187
1188 if !response.status().is_success() {
1189 return Err(EngineError::Render(format!(
1190 "Failed to download {file}: HTTP {}",
1191 response.status()
1192 )));
1193 }
1194
1195 // The downloader targets template assets (HTML/CSS/JS). Reject
1196 // anything whose Content-Type does not look textual before we
1197 // bother reading the body — stops us silently writing a binary
1198 // payload to disk and failing much later inside the parser.
1199 let content_type = response
1200 .headers()
1201 .get(reqwest::header::CONTENT_TYPE)
1202 .and_then(|v| v.to_str().ok())
1203 .unwrap_or("")
1204 .to_ascii_lowercase();
1205 let looks_textual = content_type.starts_with("text/")
1206 || content_type.starts_with("application/javascript")
1207 || content_type.starts_with("application/json")
1208 || content_type.starts_with("application/xhtml")
1209 || content_type.is_empty(); // some servers omit the header
1210 if !looks_textual {
1211 return Err(EngineError::Render(format!(
1212 "{file} has unexpected Content-Type: {content_type}"
1213 )));
1214 }
1215
1216 if let Some(len) = response.content_length() {
1217 if len as usize > MAX_BYTES {
1218 return Err(EngineError::Render(format!(
1219 "{file} too large: Content-Length {len} exceeds {MAX_BYTES}"
1220 )));
1221 }
1222 }
1223
1224 let bytes = response.bytes()?;
1225 if bytes.len() > MAX_BYTES {
1226 return Err(EngineError::Render(format!(
1227 "{file} too large after read: {} bytes exceeds {MAX_BYTES}",
1228 bytes.len()
1229 )));
1230 }
1231
1232 let mut out = File::create(&file_path)?;
1233 out.write_all(&bytes)?;
1234 Ok(())
1235 }
1236}
1237
1238// ── Async render surface (issue #37 + #38) ──────────────────────────
1239//
1240// Hidden behind `#[cfg(feature = "async")]` so default builds stay
1241// sync-only. The render machinery itself is CPU-bound and remains
1242// sync; the async surface only wraps the loader IO so callers in
1243// async runtimes don't have to spawn_blocking just to fetch a
1244// template body.
1245
1246#[cfg(feature = "async")]
1247#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
1248impl Engine {
1249 /// Async counterpart to [`Engine::render_template`]: loads the
1250 /// named template via `loader` (asynchronously), then renders
1251 /// it synchronously against `context`. Issue #37.
1252 ///
1253 /// The render itself is CPU-bound and stays sync — the async-ness
1254 /// comes from the loader IO. If you already have the template
1255 /// body in memory, prefer `render_template` directly.
1256 ///
1257 /// # Examples
1258 ///
1259 /// ```no_run
1260 /// // Requires the `async-tokio` feature + a tokio runtime.
1261 /// use staticweaver::loader_async::MemoryAsyncLoader;
1262 /// use staticweaver::{Context, Engine};
1263 /// use std::collections::HashMap;
1264 /// use std::time::Duration;
1265 ///
1266 /// # async fn run() -> Result<(), staticweaver::EngineError> {
1267 /// let mut store = HashMap::new();
1268 /// let _ = store.insert("hi".to_string(), "Hello {{name}}!".to_string());
1269 /// let loader = MemoryAsyncLoader::new(store);
1270 /// let engine = Engine::new("", Duration::from_secs(60));
1271 /// let mut ctx = Context::new();
1272 /// ctx.set("name".to_string(), "Ada".to_string());
1273 /// let out = engine.render_template_async(&loader, "hi", &ctx).await?;
1274 /// assert_eq!(out, "Hello Ada!");
1275 /// # Ok(()) }
1276 /// ```
1277 pub async fn render_template_async<L>(
1278 &self,
1279 loader: &L,
1280 name: &str,
1281 context: &Context,
1282 ) -> Result<String, EngineError>
1283 where
1284 L: staticweaver_async::AsyncTemplateLoader,
1285 {
1286 validate_name(name)?;
1287 let body = loader.load(name).await?;
1288 self.render_template(&body, context)
1289 }
1290
1291 /// Async counterpart to [`Engine::render_page`]: loads the layout
1292 /// via `loader`, applies the per-extension auto-escape policy,
1293 /// renders, and memoises the result in the same Mutex-protected
1294 /// `render_cache` the sync path uses. Issue #37.
1295 ///
1296 /// Two concurrent async tasks calling this with the same key
1297 /// race the insert harmlessly — both produce identical bytes
1298 /// because the inputs are identical.
1299 ///
1300 /// # Examples
1301 ///
1302 /// ```no_run
1303 /// // Requires the `async-tokio` feature + a tokio runtime.
1304 /// use staticweaver::loader_async::MemoryAsyncLoader;
1305 /// use staticweaver::{Context, Engine};
1306 /// use std::collections::HashMap;
1307 /// use std::time::Duration;
1308 ///
1309 /// # async fn run() -> Result<(), staticweaver::EngineError> {
1310 /// let mut store = HashMap::new();
1311 /// let _ = store.insert("page".to_string(), "v={{v}}".to_string());
1312 /// let loader = MemoryAsyncLoader::new(store);
1313 /// let engine = Engine::new("", Duration::from_secs(60));
1314 /// let mut ctx = Context::new();
1315 /// ctx.set("v".to_string(), "ok".to_string());
1316 /// let out = engine.render_page_async(&loader, &ctx, "page").await?;
1317 /// assert_eq!(out, "v=ok");
1318 /// # Ok(()) }
1319 /// ```
1320 pub async fn render_page_async<L>(
1321 &self,
1322 loader: &L,
1323 context: &Context,
1324 layout: &str,
1325 ) -> Result<String, EngineError>
1326 where
1327 L: staticweaver_async::AsyncTemplateLoader,
1328 {
1329 validate_name(layout)?;
1330
1331 let cache_key = format!("{}:{}", layout, context.hash());
1332 if let Some(cached) = self
1333 .render_cache
1334 .lock()
1335 .expect("cache poisoned")
1336 .get(&cache_key)
1337 {
1338 return Ok(cached.to_string());
1339 }
1340
1341 let template_content = loader.load(layout).await?;
1342 let output = self
1343 .renderer(self.effective_escape(layout))
1344 .render(&template_content, context)?;
1345
1346 let _ = self
1347 .render_cache
1348 .lock()
1349 .expect("cache poisoned")
1350 .insert(cache_key, output.clone());
1351
1352 Ok(output)
1353 }
1354
1355 /// Async streaming sink — issue #38. Mirror of
1356 /// [`Engine::render_to`] for `AsyncWrite`-flavoured destinations
1357 /// (`tokio::fs::File`, `tokio::net::TcpStream`, an Axum body
1358 /// channel). The render itself stays sync; the bytes flush
1359 /// through the async writer.
1360 ///
1361 /// Requires the `async-tokio` feature for the `AsyncWriteExt`
1362 /// extension trait.
1363 ///
1364 /// # Examples
1365 ///
1366 /// ```no_run
1367 /// // Requires the `async-tokio` feature + a tokio runtime.
1368 /// use staticweaver::{Context, Engine};
1369 /// use std::time::Duration;
1370 ///
1371 /// # async fn run() -> Result<(), staticweaver::EngineError> {
1372 /// let engine = Engine::new("", Duration::from_secs(60));
1373 /// let mut ctx = Context::new();
1374 /// ctx.set("who".to_string(), "world".to_string());
1375 /// let mut sink: Vec<u8> = Vec::new();
1376 /// engine.render_to_async("hi {{who}}", &ctx, &mut sink).await?;
1377 /// assert_eq!(&sink, b"hi world");
1378 /// # Ok(()) }
1379 /// ```
1380 #[cfg(feature = "async-tokio")]
1381 #[cfg_attr(docsrs, doc(cfg(feature = "async-tokio")))]
1382 pub async fn render_to_async<W>(
1383 &self,
1384 template: &str,
1385 context: &Context,
1386 writer: &mut W,
1387 ) -> Result<(), EngineError>
1388 where
1389 W: tokio::io::AsyncWrite + Unpin + Send,
1390 {
1391 use tokio::io::AsyncWriteExt;
1392 let body = self.render_template(template, context)?;
1393 writer.write_all(body.as_bytes()).await?;
1394 Ok(())
1395 }
1396
1397 /// Page-flavoured async streaming sink — issue #38. Combines
1398 /// async load + sync render + async write into one call. Errors
1399 /// surface as `EngineError`.
1400 ///
1401 /// # Examples
1402 ///
1403 /// ```no_run
1404 /// // Requires the `async-tokio` feature + a tokio runtime.
1405 /// use staticweaver::loader_async::MemoryAsyncLoader;
1406 /// use staticweaver::{Context, Engine};
1407 /// use std::collections::HashMap;
1408 /// use std::time::Duration;
1409 ///
1410 /// # async fn run() -> Result<(), staticweaver::EngineError> {
1411 /// let mut store = HashMap::new();
1412 /// let _ = store.insert("p".to_string(), "[{{a}}]".to_string());
1413 /// let loader = MemoryAsyncLoader::new(store);
1414 /// let engine = Engine::new("", Duration::from_secs(60));
1415 /// let mut ctx = Context::new();
1416 /// ctx.set("a".to_string(), "ok".to_string());
1417 /// let mut sink: Vec<u8> = Vec::new();
1418 /// engine.render_page_to_async(&loader, &ctx, "p", &mut sink).await?;
1419 /// assert_eq!(&sink, b"[ok]");
1420 /// # Ok(()) }
1421 /// ```
1422 #[cfg(feature = "async-tokio")]
1423 #[cfg_attr(docsrs, doc(cfg(feature = "async-tokio")))]
1424 pub async fn render_page_to_async<L, W>(
1425 &self,
1426 loader: &L,
1427 context: &Context,
1428 layout: &str,
1429 writer: &mut W,
1430 ) -> Result<(), EngineError>
1431 where
1432 L: staticweaver_async::AsyncTemplateLoader,
1433 W: tokio::io::AsyncWrite + Unpin + Send,
1434 {
1435 use tokio::io::AsyncWriteExt;
1436 let body =
1437 self.render_page_async(loader, context, layout).await?;
1438 writer.write_all(body.as_bytes()).await?;
1439 Ok(())
1440 }
1441}
1442
1443/// Utility function to check if a given path is a URL.
1444///
1445/// # Arguments
1446///
1447/// * `path` - The path to check.
1448///
1449/// # Returns
1450///
1451/// `true` if the path is a URL, `false` otherwise.
1452fn is_url(path: &str) -> bool {
1453 path.starts_with("http://") || path.starts_with("https://")
1454}
1455
1456#[cfg(test)]
1457#[path = "engine_tests.rs"]
1458mod tests;