Skip to main content

rustango_cms/
snippet_render.rs

1//! `snippet_html(type=…, id=N)` Tera helper — per-snippet template
2//! rendering.
3//!
4//! Pairs with [`crate::library::LibraryTypeHandler::render_template`]:
5//! handlers that declare a template have their rows pre-rendered
6//! through it at public-render time. Templates fetch the rendered
7//! HTML via this function keyed on `(type, id)`.
8//!
9//! A type may instead let each element name its own template, by
10//! returning `true` from
11//! [`allows_element_template`](crate::library::LibraryTypeHandler::allows_element_template);
12//! the name then comes from that row's `data.template` and falls back
13//! to the type's own. That is what makes an element the whole unit —
14//! its content and its markup travel together — and it needs no
15//! migration, because `cms_snippet.data` is already free-form JSON.
16//!
17//! The name resolves against the Tera instance handed to [`prefetch`],
18//! which the public router has already overlaid with the tenant's
19//! templates (`router.rs` `tera_for`). So a template written into
20//! `templates_tenants/<org>/…` — by the admin editor or the
21//! `write_template` MCP tool — is renderable by name here, with no
22//! per-render `add_raw_template`.
23//!
24//! Same thread-local install pattern as [`crate::page_url`] /
25//! [`crate::auto_menu`] / [`crate::children_filtered`] / [`crate::richtext`]:
26//! the public-render pipeline pre-fetches + pre-renders into a
27//! `{(type, id) → html}` map, installs it in a thread-local for the
28//! duration of `tera.render`, and clears on guard drop.
29//!
30//! ## Usage in templates
31//!
32//! ```text
33//! {{ snippet_html(type="Category", id=4) | safe }}
34//! ```
35//!
36//! Missing entries (unknown type, unknown id, type without a
37//! `render_template`) → empty string.
38
39use std::cell::RefCell;
40use std::collections::HashMap;
41use std::sync::Arc;
42
43use tera::{Function, Tera, Value};
44
45/// Composite key for the per-snippet HTML map.
46type Key = (String, i64);
47
48thread_local! {
49    static CURRENT_SNIPPETS_HTML: RefCell<Option<Arc<HashMap<Key, String>>>>
50        = const { RefCell::new(None) };
51}
52
53/// RAII guard. While in scope `snippet_html(...)` resolves against
54/// the installed map; on drop the thread-local clears.
55#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
56pub struct SnippetHtmlGuard {
57    _priv: (),
58}
59
60impl Drop for SnippetHtmlGuard {
61    fn drop(&mut self) {
62        CURRENT_SNIPPETS_HTML.with(|cell| {
63            *cell.borrow_mut() = None;
64        });
65    }
66}
67
68/// Install a `(type, id) → html` map for the duration of the
69/// returned guard. Bound by the public-render pipeline right before
70/// `tera.render`.
71pub fn install(map: HashMap<Key, String>) -> SnippetHtmlGuard {
72    CURRENT_SNIPPETS_HTML.with(|cell| {
73        *cell.borrow_mut() = Some(Arc::new(map));
74    });
75    SnippetHtmlGuard { _priv: () }
76}
77
78/// Register the `snippet_html` Tera function. Wired from
79/// [`crate::urls::register_tera_helpers`].
80pub fn register_tera_function(tera: &mut Tera) {
81    tera.register_function("snippet_html", SnippetHtmlFn);
82}
83
84/// `is_safe = true` — output is sanitized HTML produced by the
85/// snippet's own template (which itself can apply `| safe` on
86/// trusted body fields). Autoescape would mangle the rendered
87/// tags into entities otherwise.
88struct SnippetHtmlFn;
89
90impl Function for SnippetHtmlFn {
91    fn call(&self, args: &HashMap<String, Value>) -> tera::Result<Value> {
92        let ty = args.get("type").and_then(Value::as_str).unwrap_or("");
93        let id = args.get("id").and_then(Value::as_i64).unwrap_or(0);
94        if ty.is_empty() || id <= 0 {
95            return Ok(Value::String(String::new()));
96        }
97        let html = CURRENT_SNIPPETS_HTML.with(|cell| {
98            cell.borrow()
99                .as_ref()
100                .and_then(|m| m.get(&(ty.to_owned(), id)).cloned())
101                .unwrap_or_default()
102        });
103        Ok(Value::String(html))
104    }
105    fn is_safe(&self) -> bool {
106        true
107    }
108}
109
110/// Pre-render every snippet whose handler declares a
111/// `render_template`. Returns a `(type, id) → html` map ready to
112/// `install` for the render duration.
113///
114/// Failures during a single template render are best-effort: the
115/// row's slot is left empty rather than crashing the whole render
116/// (the snippet is missing in the output, the rest of the page
117/// still ships).
118///
119/// # Errors
120/// None — degrades to an empty map on snippet-fetch failure (the
121/// whole call short-circuits, every `snippet_html(...)` returns
122/// empty).
123pub async fn prefetch(
124    pool: &rustango::sql::Pool,
125    tera: &Tera,
126    locale_id: Option<i64>,
127) -> HashMap<Key, String> {
128    use rustango::core::Column as _;
129    use rustango::sql::FetcherPool as _;
130    let mut out: HashMap<Key, String> = HashMap::new();
131    // Walk every registered library handler that declares a
132    // template; for each, fetch every row of that type and render
133    // it through the template.
134    for handler in crate::library::registered_handlers() {
135        let type_default = handler.render_template();
136        let per_element = handler.allows_element_template();
137        // Nothing to render: no type-wide template, and rows of this
138        // type aren't allowed to name one either.
139        if type_default.is_none() && !per_element {
140            continue;
141        }
142        let type_name = handler.type_name();
143        let rows = match crate::snippet::Snippet::objects()
144            .where_(crate::snippet::Snippet::type_name.eq(type_name.to_owned()))
145            .fetch(pool)
146            .await
147        {
148            Ok(r) => r,
149            Err(e) => {
150                tracing::warn!(
151                    target: "rustango_cms::snippet_render",
152                    error = %e,
153                    type_name = %type_name,
154                    "snippet prefetch failed for type; skipping",
155                );
156                continue;
157            }
158        };
159        // #409 — per-locale field overrides for this type's rows (one
160        // batched fetch). Empty on the default locale.
161        let translations = match locale_id {
162            Some(lid) => {
163                let ids: Vec<i64> = rows.iter().filter_map(|r| r.id.get().copied()).collect();
164                crate::snippet_translation::fetch_for_snippets(pool, &ids, lid)
165                    .await
166                    .unwrap_or_default()
167            }
168            None => HashMap::new(),
169        };
170        for row in rows {
171            let Some(id) = row.id.get().copied() else {
172                continue;
173            };
174            let mut ctx = tera::Context::new();
175            let mut snippet_value = serde_json::to_value(&row).unwrap_or(serde_json::Value::Null);
176            if let Some(overrides) = translations.get(&id) {
177                apply_overrides(&mut snippet_value, overrides);
178            }
179            // Resolve after the translation overlay: a locale may
180            // override `data.template` to swap markup per language.
181            let template = match per_element
182                .then(|| element_template(&snippet_value))
183                .flatten()
184            {
185                Some(name) => name,
186                None => match type_default {
187                    Some(t) => t.to_owned(),
188                    // Per-element type, and this row names nothing.
189                    // Not an error: rows opt in one at a time.
190                    None => continue,
191                },
192            };
193            ctx.insert("snippet", &snippet_value);
194            match tera.render(&template, &ctx) {
195                Ok(html) => {
196                    out.insert((type_name.to_owned(), id), html);
197                }
198                Err(e) => {
199                    tracing::warn!(
200                        target: "rustango_cms::snippet_render",
201                        error = %e,
202                        type_name = %type_name,
203                        id,
204                        template = %template,
205                        "snippet template render failed; leaving slot empty",
206                    );
207                }
208            }
209        }
210    }
211    out
212}
213
214/// The template an individual element names in its `data.template`,
215/// for types that opted in via
216/// [`crate::library::LibraryTypeHandler::allows_element_template`].
217///
218/// The name must pass [`crate::tenant_templates::safe_name`], the rule for
219/// every editor-supplied template name: relative, `.html`, no
220/// traversal. Tera resolves names against its registered set, so a bad
221/// name could not load a file anyway; refusing it keeps a broken value
222/// from looking like a working one.
223fn element_template(snippet_value: &Value) -> Option<String> {
224    let name = snippet_value.get("data")?.get("template")?.as_str()?;
225    crate::tenant_templates::safe_name(name).ok()
226}
227
228/// Apply per-locale translation `overrides` onto a snippet's JSON value.
229/// Top-level fields (`title`, `body_markdown`, …) are replaced
230/// in place; a `data.<key>` path writes into the snippet's `data`
231/// object. Non-object values + missing `data` are created as needed.
232fn apply_overrides(value: &mut Value, overrides: &HashMap<String, String>) {
233    let Some(obj) = value.as_object_mut() else {
234        return;
235    };
236    for (path, v) in overrides {
237        if let Some(key) = path.strip_prefix("data.") {
238            let data = obj
239                .entry("data")
240                .or_insert_with(|| Value::Object(serde_json::Map::new()));
241            if let Some(map) = data.as_object_mut() {
242                map.insert(key.to_owned(), Value::String(v.clone()));
243            }
244        } else {
245            obj.insert(path.clone(), Value::String(v.clone()));
246        }
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use tera::{Context, Tera};
254
255    fn fresh_tera() -> Tera {
256        let mut tera = Tera::default();
257        register_tera_function(&mut tera);
258        tera
259    }
260
261    fn render(tera: &Tera, src: &str) -> String {
262        let mut t = tera.clone();
263        t.add_raw_template("t.html", src).unwrap();
264        t.render("t.html", &Context::new()).unwrap()
265    }
266
267    fn with_template(name: &str) -> Value {
268        serde_json::json!({ "data": { "template": name } })
269    }
270
271    #[test]
272    fn element_template_reads_a_plain_relative_name() {
273        assert_eq!(
274            element_template(&with_template("widgets/donations.html")),
275            Some("widgets/donations.html".to_owned())
276        );
277    }
278
279    #[test]
280    fn element_template_trims_surrounding_whitespace() {
281        assert_eq!(
282            element_template(&with_template("  widgets/a.html \n")),
283            Some("widgets/a.html".to_owned())
284        );
285    }
286
287    #[test]
288    fn element_template_absent_when_unset_or_wrong_shape() {
289        assert_eq!(element_template(&serde_json::json!({})), None);
290        assert_eq!(element_template(&serde_json::json!({"data": {}})), None);
291        // A non-string `template` is a malformed row, not a name.
292        assert_eq!(
293            element_template(&serde_json::json!({"data": {"template": 7}})),
294            None
295        );
296    }
297
298    #[test]
299    fn element_template_refuses_traversal_and_absolute_names() {
300        for bad in [
301            "",
302            "   ",
303            "/etc/passwd",
304            "../../secrets.html",
305            "widgets/../../../x.html",
306            "widgets\\win.html",
307            // #661 — what the weaker copy let through.
308            ".env",
309            "a//b.html",
310            "a/./b.html",
311            "widgets/donations",
312        ] {
313            assert_eq!(
314                element_template(&with_template(bad)),
315                None,
316                "should have refused {bad:?}"
317            );
318        }
319    }
320
321    #[test]
322    fn element_template_allows_dots_inside_a_segment() {
323        // `..` is only a traversal as a whole segment — a file called
324        // `a..b.html` is an ordinary name and must not be refused.
325        assert_eq!(
326            element_template(&with_template("widgets/a..b.html")),
327            Some("widgets/a..b.html".to_owned())
328        );
329    }
330
331    #[test]
332    fn apply_overrides_replaces_top_level_and_data_paths() {
333        // #409 — title/body_markdown replace in place; `data.<key>`
334        // writes into the data object.
335        let mut v = serde_json::json!({
336            "title": "Hi", "body_markdown": "en body", "data": {"cta": "Click"}
337        });
338        let mut o = HashMap::new();
339        o.insert("title".to_owned(), "Bonjour".to_owned());
340        o.insert("body_markdown".to_owned(), "corps fr".to_owned());
341        o.insert("data.cta".to_owned(), "Cliquez".to_owned());
342        super::apply_overrides(&mut v, &o);
343        assert_eq!(v["title"], serde_json::json!("Bonjour"));
344        assert_eq!(v["body_markdown"], serde_json::json!("corps fr"));
345        assert_eq!(v["data"]["cta"], serde_json::json!("Cliquez"));
346    }
347
348    #[test]
349    fn apply_overrides_creates_missing_data_object() {
350        let mut v = serde_json::json!({ "title": "Hi" });
351        let mut o = HashMap::new();
352        o.insert("data.x".to_owned(), "y".to_owned());
353        super::apply_overrides(&mut v, &o);
354        assert_eq!(v["data"]["x"], serde_json::json!("y"));
355    }
356
357    #[test]
358    fn returns_empty_when_nothing_installed() {
359        let tera = fresh_tera();
360        let out = render(&tera, r#"x{{ snippet_html(type="Category", id=1) }}y"#);
361        assert_eq!(out, "xy");
362    }
363
364    #[test]
365    fn resolves_known_type_and_id() {
366        let mut m = HashMap::new();
367        m.insert(
368            ("Category".to_owned(), 4i64),
369            "<span>rust</span>".to_owned(),
370        );
371        let _g = install(m);
372        let tera = fresh_tera();
373        let out = render(&tera, r#"{{ snippet_html(type="Category", id=4) }}"#);
374        assert_eq!(out, "<span>rust</span>");
375    }
376
377    #[test]
378    fn unknown_type_returns_empty() {
379        let mut m = HashMap::new();
380        m.insert(
381            ("Category".to_owned(), 4i64),
382            "<span>rust</span>".to_owned(),
383        );
384        let _g = install(m);
385        let tera = fresh_tera();
386        let out = render(&tera, r#"x{{ snippet_html(type="Author", id=4) }}y"#);
387        assert_eq!(out, "xy");
388    }
389
390    #[test]
391    fn unknown_id_returns_empty() {
392        let mut m = HashMap::new();
393        m.insert(
394            ("Category".to_owned(), 4i64),
395            "<span>rust</span>".to_owned(),
396        );
397        let _g = install(m);
398        let tera = fresh_tera();
399        let out = render(&tera, r#"x{{ snippet_html(type="Category", id=99) }}y"#);
400        assert_eq!(out, "xy");
401    }
402
403    #[test]
404    fn missing_args_return_empty() {
405        let _g = install(HashMap::new());
406        let tera = fresh_tera();
407        let out = render(&tera, r#"x{{ snippet_html(type="Category") }}y"#);
408        assert_eq!(out, "xy");
409        let out2 = render(&tera, r#"x{{ snippet_html(id=4) }}y"#);
410        assert_eq!(out2, "xy");
411    }
412
413    #[test]
414    fn output_is_marked_safe() {
415        // Without is_safe, `<span>` would land as `&lt;span&gt;`.
416        let mut m = HashMap::new();
417        m.insert(("X".to_owned(), 1i64), "<b>ok</b>".to_owned());
418        let _g = install(m);
419        let tera = fresh_tera();
420        let out = render(&tera, r#"{{ snippet_html(type="X", id=1) }}"#);
421        assert!(out.contains("<b>ok</b>"), "got `{out}`");
422    }
423
424    #[test]
425    fn guard_clears_thread_local() {
426        {
427            let mut m = HashMap::new();
428            m.insert(("X".to_owned(), 1i64), "y".to_owned());
429            let _g = install(m);
430            let tera = fresh_tera();
431            assert_eq!(render(&tera, r#"{{ snippet_html(type="X", id=1) }}"#), "y");
432        }
433        let tera = fresh_tera();
434        assert_eq!(
435            render(&tera, r#"x{{ snippet_html(type="X", id=1) }}y"#),
436            "xy"
437        );
438    }
439}