Skip to main content

rustango_cms/
site_setting.rs

1//! Per-tenant site settings.
2//!
3//! Editor-managed singleton key-value rows. Templates read them via
4//! the `{{ site_setting(scope='footer') }}` Tera function; admins
5//! manage them under Settings → Site settings.
6//!
7//! Each `scope` (e.g. "footer", "contact", "social") gets exactly one
8//! row with a JSON value column. Two editing modes share that storage:
9//!
10//! - **Free-form** (default): editors type raw JSON in a textarea.
11//!   Covers ad-hoc scopes with zero host boilerplate.
12//! - **Typed**: a host crate registers a [`SiteSettingSchema`]
13//!   for a scope via [`crate::register_site_setting!`], declaring a
14//!   list of [`Widget`]s. The admin then renders a real form (the same
15//!   `_widget.html` machinery page-type fields use), validates required
16//!   fields, and coerces each input back into the `value_json` object
17//!   keyed by field `name`. Templates read both modes identically:
18//!   `{{ site_setting(scope='footer').site_name }}`.
19
20use chrono::{DateTime, Utc};
21use rustango::sql::Auto;
22use rustango::Model;
23use serde::{Deserialize, Serialize};
24
25use crate::widget::{Widget, WidgetKind};
26
27#[derive(Model, Debug, Clone, Serialize, Deserialize)]
28#[rustango(
29    table = "cms_site_setting",
30    app = "cms",
31    display = "scope",
32    admin(list_display = "scope, updated_at", ordering = "scope",)
33)]
34pub struct SiteSetting {
35    #[rustango(primary_key)]
36    pub id: Auto<i64>,
37
38    /// Stable identifier for this settings row — e.g. `"footer"`,
39    /// `"contact"`, `"social"`. Application-enforced UNIQUE within
40    /// the tenant (avoids SQL composite-unique dialect drift).
41    #[rustango(max_length = 64, index)]
42    pub scope: String,
43
44    /// Free-form JSON object. Tera templates read via
45    /// `{{ site_setting(scope='footer').field }}`. Empty object
46    /// `{}` is a valid initial state.
47    pub value_json: serde_json::Value,
48
49    #[rustango(auto_now)]
50    pub updated_at: Auto<DateTime<Utc>>,
51}
52
53/// Fetch a setting row by scope. Returns `None` when no row exists —
54/// templates should treat absence as "settings haven't been
55/// configured yet" rather than erroring.
56///
57/// # Errors
58/// Driver / query failures.
59pub async fn get(
60    pool: &rustango::sql::Pool,
61    scope: &str,
62) -> Result<Option<SiteSetting>, rustango::sql::ExecError> {
63    use rustango::core::Column as _;
64    use rustango::sql::FetcherPool as _;
65    let rows: Vec<SiteSetting> = SiteSetting::objects()
66        .where_(SiteSetting::scope.eq(scope.to_owned()))
67        .fetch(pool)
68        .await?;
69    Ok(rows.into_iter().next())
70}
71
72/// UPSERT a setting by scope.
73///
74/// # Errors
75/// Driver / query failures.
76pub async fn upsert(
77    pool: &rustango::sql::Pool,
78    scope: &str,
79    value: serde_json::Value,
80) -> Result<SiteSetting, rustango::sql::ExecError> {
81    if let Some(mut row) = get(pool, scope).await? {
82        row.value_json = value;
83        row.save(pool).await?;
84        return Ok(row);
85    }
86    let mut row = SiteSetting {
87        id: Auto::Unset,
88        scope: scope.to_owned(),
89        value_json: value,
90        updated_at: Auto::Unset,
91    };
92    row.insert(pool).await?;
93    Ok(row)
94}
95
96/// List every setting row in the tenant, sorted by scope.
97///
98/// # Errors
99/// Driver / query failures.
100pub async fn list_all(
101    pool: &rustango::sql::Pool,
102) -> Result<Vec<SiteSetting>, rustango::sql::ExecError> {
103    use rustango::sql::FetcherPool as _;
104    SiteSetting::objects()
105        .order_by(&[("scope", false)])
106        .fetch(pool)
107        .await
108}
109
110// ---- #406 — typed settings registry ------------------------------
111
112/// A typed schema for one settings `scope`: a human label + the list
113/// of typed fields editors fill in (instead of raw JSON). Host crates
114/// register one per scope via [`crate::register_site_setting!`].
115///
116/// `fields` returns a *fresh* `Vec<Widget>` each call so the admin can
117/// prefill values into the clones without mutating shared state. Each
118/// field `name` becomes a key in the stored `value_json` object, and
119/// its [`WidgetKind`] drives both the rendered input and how the
120/// submitted string is coerced back into JSON (see
121/// [`value_json_from_form`]).
122pub struct SiteSettingSchema {
123    pub scope: &'static str,
124    pub label: &'static str,
125    pub fields: fn() -> Vec<Widget>,
126}
127
128inventory::collect!(SiteSettingSchema);
129
130/// The registered schema for `scope`, if any. Unregistered scopes fall
131/// back to the free-form JSON editor.
132#[must_use]
133pub fn schema_for(scope: &str) -> Option<&'static SiteSettingSchema> {
134    inventory::iter::<SiteSettingSchema>
135        .into_iter()
136        .find(|s| s.scope == scope)
137}
138
139/// Every registered schema, sorted by scope. The admin list surfaces
140/// these even before a row exists, so typed settings are always
141/// discoverable in the settings menu.
142#[must_use]
143pub fn registered_schemas() -> Vec<&'static SiteSettingSchema> {
144    let mut v: Vec<_> = inventory::iter::<SiteSettingSchema>.into_iter().collect();
145    v.sort_by_key(|s| s.scope);
146    v
147}
148
149/// Register a typed schema for a site-settings `scope`.
150///
151/// ```ignore
152/// use rustango_cms::widget::{Widget, WidgetKind};
153/// rustango_cms::register_site_setting!("footer", "Footer", || vec![
154///     Widget::new(WidgetKind::Text, "site_name", "Site name").required(),
155///     Widget::new(WidgetKind::Textarea, "copyright", "Copyright notice"),
156///     Widget::new(WidgetKind::Boolean, "show_social", "Show social links"),
157/// ]);
158/// ```
159///
160/// The admin then renders typed inputs for `footer` instead of a JSON
161/// textarea, enforces `required` fields, and stores each value under
162/// its field `name` in `value_json`. Templates are unchanged:
163/// `{{ site_setting(scope='footer').site_name }}`.
164#[macro_export]
165macro_rules! register_site_setting {
166    ($scope:expr, $label:expr, $fields:expr $(,)?) => {
167        $crate::inventory::submit! {
168            $crate::site_setting::SiteSettingSchema {
169                scope: $scope,
170                label: $label,
171                fields: $fields,
172            }
173        }
174    };
175}
176
177/// Clone `fields` and prefill each widget's `value` from the matching
178/// key in `stored` (the row's `value_json`). The inverse of
179/// [`value_json_from_form`]:
180/// - booleans → `"on"` when truthy (so the checkbox renders checked),
181/// - multi-value widgets → the JSON-array string the editor expects,
182/// - everything else → the scalar without JSON quoting (strings
183///   as-is, numbers as their decimal text).
184#[must_use]
185pub fn prefill_widgets(fields: Vec<Widget>, stored: &serde_json::Value) -> Vec<Widget> {
186    fields
187        .into_iter()
188        .map(|mut w| {
189            if let Some(v) = stored.get(&w.name) {
190                w.value = json_to_widget_value(w.kind, v);
191            }
192            w
193        })
194        .collect()
195}
196
197fn json_to_widget_value(kind: WidgetKind, v: &serde_json::Value) -> String {
198    if kind == WidgetKind::Boolean {
199        let truthy = v.as_bool().unwrap_or(false)
200            || v.as_str()
201                .is_some_and(|s| s == "on" || s == "true" || s == "1")
202            || v.as_i64().is_some_and(|n| n != 0);
203        return if truthy {
204            "on".to_owned()
205        } else {
206            String::new()
207        };
208    }
209    if kind.is_multi_value() {
210        return match v {
211            // Stored as a JSON array → hand the editor the array STRING
212            // it round-trips through the hidden multi-value input.
213            serde_json::Value::Array(_) => v.to_string(),
214            serde_json::Value::String(s) => s.clone(),
215            _ => String::new(),
216        };
217    }
218    match v {
219        serde_json::Value::String(s) => s.clone(),
220        serde_json::Value::Null => String::new(),
221        // Numbers/bools rendered as their bare text (no JSON quoting).
222        other => other.to_string(),
223    }
224}
225
226/// Build a `value_json` object from a submitted form map, coercing
227/// each value by its widget kind:
228/// - numeric kinds → a JSON number when parseable (blank = dropped,
229///   unparseable = kept as a string so nothing is silently lost),
230/// - booleans → `true` only when the checkbox key is present,
231/// - multi-value kinds → the posted JSON-array string parsed to an
232///   array (falls back to a string on parse failure),
233/// - everything else → a JSON string (empty strings are kept so a
234///   template can tell "set to empty" from "never set").
235///
236/// Keys absent from `fields` are ignored, so the CSRF token and any
237/// stray inputs never leak into the stored value.
238#[must_use]
239pub fn value_json_from_form(
240    fields: &[Widget],
241    form: &std::collections::HashMap<String, String>,
242) -> serde_json::Value {
243    let mut obj = serde_json::Map::new();
244    for w in fields {
245        if w.kind == WidgetKind::Boolean {
246            obj.insert(
247                w.name.clone(),
248                serde_json::Value::Bool(form.contains_key(&w.name)),
249            );
250            continue;
251        }
252        let Some(raw) = form.get(&w.name) else {
253            continue;
254        };
255        let value = match w.kind {
256            WidgetKind::Integer => {
257                let t = raw.trim();
258                if t.is_empty() {
259                    continue;
260                }
261                t.parse::<i64>().map_or_else(
262                    |_| serde_json::Value::String(t.to_owned()),
263                    |n| serde_json::json!(n),
264                )
265            }
266            WidgetKind::Number | WidgetKind::Float | WidgetKind::Range => {
267                let t = raw.trim();
268                if t.is_empty() {
269                    continue;
270                }
271                t.parse::<f64>().map_or_else(
272                    |_| serde_json::Value::String(t.to_owned()),
273                    |n| serde_json::json!(n),
274                )
275            }
276            _ if w.kind.is_multi_value() => serde_json::from_str::<serde_json::Value>(raw)
277                .unwrap_or_else(|_| serde_json::Value::String(raw.clone())),
278            _ => serde_json::Value::String(raw.clone()),
279        };
280        obj.insert(w.name.clone(), value);
281    }
282    serde_json::Value::Object(obj)
283}
284
285/// Labels of `required` fields left blank in `form`. The submit
286/// handler turns a non-empty result into a validation error. Boolean
287/// (checkbox) widgets are skipped — "required checkbox" has no settled
288/// UX here and a missing key legitimately means `false`.
289#[must_use]
290pub fn missing_required(
291    fields: &[Widget],
292    form: &std::collections::HashMap<String, String>,
293) -> Vec<String> {
294    fields
295        .iter()
296        .filter(|w| w.required && w.kind != WidgetKind::Boolean)
297        .filter(|w| form.get(&w.name).is_none_or(|s| s.trim().is_empty()))
298        .map(|w| w.label.clone())
299        .collect()
300}
301
302// ---- #245 — `site_setting(scope=…)` Tera helper -------------------
303
304/// Pre-fetch every site-setting row + group them into a
305/// `scope → value_json` map. Public-render installs this map in a
306/// thread-local that the `site_setting(scope=…)` Tera function
307/// reads. Bounded by the count of distinct scopes (typically tens),
308/// so one query per render covers every reference.
309///
310/// # Errors
311/// None — failures degrade to an empty map; templates see
312/// `Value::Null` for every scope lookup.
313pub async fn prefetch_for_render(
314    pool: &rustango::sql::Pool,
315    locale_code: Option<&str>,
316) -> std::collections::HashMap<String, serde_json::Value> {
317    let rows = list_all(pool).await.unwrap_or_default();
318    rows.into_iter()
319        .map(|r| (r.scope, localize(&r.value_json, locale_code)))
320        .collect()
321}
322
323// ---- per-language values ------------------------------------------
324
325/// Key inside `value_json` holding translations: `{"fr": {"footer": "…"}}`.
326/// Kept in the same row so settings need no extra table; templates never
327/// see it (see [`localize`]).
328pub const I18N_KEY: &str = "_i18n";
329
330/// A setting's value as a template sees it in `locale` (a locale code;
331/// `None` = the default language): the translated text fields laid over
332/// the original, empty translations ignored, and the `_i18n` bag removed.
333#[must_use]
334pub fn localize(value: &serde_json::Value, locale: Option<&str>) -> serde_json::Value {
335    let Some(obj) = value.as_object() else {
336        return value.clone();
337    };
338    let mut out = obj.clone();
339    let bag = out.remove(I18N_KEY);
340    if let Some(tr) = locale.and_then(|code| bag.as_ref()?.get(code)?.as_object().cloned()) {
341        for (k, v) in tr {
342            if v.as_str().is_some_and(|t| !t.trim().is_empty()) {
343                out.insert(k, v);
344            }
345        }
346    }
347    serde_json::Value::Object(out)
348}
349
350/// The `locale` translations stored in `value`, by field key.
351#[must_use]
352pub fn translations(value: &serde_json::Value, locale: &str) -> serde_json::Map<String, serde_json::Value> {
353    value
354        .get(I18N_KEY)
355        .and_then(|b| b.get(locale))
356        .and_then(serde_json::Value::as_object)
357        .cloned()
358        .unwrap_or_default()
359}
360
361/// Replace the `locale` translations in `value` with `fields` (empty
362/// strings dropped; no fields left → the language is removed).
363pub fn set_translations(
364    value: &mut serde_json::Value,
365    locale: &str,
366    fields: serde_json::Map<String, serde_json::Value>,
367) {
368    if !value.is_object() {
369        *value = serde_json::json!({});
370    }
371    let obj = value.as_object_mut().expect("object above");
372    let bag = obj
373        .entry(I18N_KEY)
374        .or_insert_with(|| serde_json::json!({}));
375    if !bag.is_object() {
376        *bag = serde_json::json!({});
377    }
378    let bag = bag.as_object_mut().expect("object above");
379    let kept: serde_json::Map<String, serde_json::Value> = fields
380        .into_iter()
381        .filter(|(_, v)| v.as_str().is_some_and(|t| !t.trim().is_empty()))
382        .collect();
383    if kept.is_empty() {
384        bag.remove(locale);
385    } else {
386        bag.insert(locale.to_owned(), serde_json::Value::Object(kept));
387    }
388    if bag.is_empty() {
389        obj.remove(I18N_KEY);
390    }
391}
392
393/// Carry `old`'s translations over to `new` — the typed form rebuilds the
394/// whole value from its fields and must not drop them.
395pub fn keep_translations(old: &serde_json::Value, new: &mut serde_json::Value) {
396    if let (Some(bag), Some(obj)) = (old.get(I18N_KEY), new.as_object_mut()) {
397        obj.insert(I18N_KEY.to_owned(), bag.clone());
398    }
399}
400
401thread_local! {
402    /// Per-render `scope → value_json` map. Installed by
403    /// [`install`], cleared on guard drop.
404    static CURRENT_SITE_SETTINGS: std::cell::RefCell<
405        Option<std::sync::Arc<std::collections::HashMap<String, serde_json::Value>>>,
406    > = const { std::cell::RefCell::new(None) };
407}
408
409/// RAII guard for the site-settings map. Returned by [`install`];
410/// drop clears the thread-local.
411#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
412pub struct SiteSettingsGuard {
413    _priv: (),
414}
415
416impl Drop for SiteSettingsGuard {
417    fn drop(&mut self) {
418        CURRENT_SITE_SETTINGS.with(|cell| {
419            *cell.borrow_mut() = None;
420        });
421    }
422}
423
424/// Install a pre-fetched `scope → value_json` map for the duration
425/// of the returned guard. The `site_setting(scope=…)` Tera function
426/// reads against this map.
427pub fn install(map: std::collections::HashMap<String, serde_json::Value>) -> SiteSettingsGuard {
428    CURRENT_SITE_SETTINGS.with(|cell| {
429        *cell.borrow_mut() = Some(std::sync::Arc::new(map));
430    });
431    SiteSettingsGuard { _priv: () }
432}
433
434/// Register the `site_setting(scope=…)` Tera function. Wired from
435/// [`crate::urls::register_tera_helpers`].
436pub fn register_tera_function(tera: &mut tera::Tera) {
437    tera.register_function("site_setting", SiteSettingFn);
438}
439
440struct SiteSettingFn;
441
442impl tera::Function for SiteSettingFn {
443    fn call(
444        &self,
445        args: &std::collections::HashMap<String, tera::Value>,
446    ) -> tera::Result<tera::Value> {
447        let scope = args
448            .get("scope")
449            .and_then(tera::Value::as_str)
450            .unwrap_or("");
451        if scope.is_empty() {
452            return Ok(tera::Value::Null);
453        }
454        let value = CURRENT_SITE_SETTINGS.with(|cell| {
455            cell.borrow()
456                .as_ref()
457                .and_then(|m| m.get(scope).cloned())
458                .unwrap_or(tera::Value::Null)
459        });
460        Ok(value)
461    }
462}
463
464#[cfg(test)]
465mod schema_tests {
466
467    #[test]
468    fn localize_overlays_text_and_hides_the_bag() {
469        let v = serde_json::json!({
470            "shop_name": "Clay & Kiln", "footer": "Made by hand.",
471            "_i18n": { "fr": { "footer": "Fait main.", "shop_name": "" } }
472        });
473        assert_eq!(super::localize(&v, Some("fr")), serde_json::json!({"shop_name": "Clay & Kiln", "footer": "Fait main."}));
474        assert_eq!(super::localize(&v, None), serde_json::json!({"shop_name": "Clay & Kiln", "footer": "Made by hand."}));
475        assert_eq!(super::localize(&v, Some("de")), super::localize(&v, None));
476    }
477
478    #[test]
479    fn set_and_keep_translations() {
480        let mut v = serde_json::json!({"footer": "Made by hand."});
481        let mut f = serde_json::Map::new();
482        f.insert("footer".into(), serde_json::json!("Fait main."));
483        f.insert("shop_name".into(), serde_json::json!("  "));
484        super::set_translations(&mut v, "fr", f);
485        assert_eq!(super::translations(&v, "fr"), serde_json::json!({"footer": "Fait main."}).as_object().unwrap().clone());
486        let mut saved = serde_json::json!({"footer": "Made by hand, fired with care."});
487        super::keep_translations(&v, &mut saved);
488        assert_eq!(saved["_i18n"]["fr"]["footer"], "Fait main.");
489        super::set_translations(&mut saved, "fr", serde_json::Map::new());
490        assert!(saved.get("_i18n").is_none(), "no languages left → no bag");
491    }
492
493    use super::*;
494    use std::collections::HashMap;
495
496    // A throwaway typed schema registered into the test binary's
497    // inventory so `schema_for` / `registered_schemas` have something
498    // to find. Real hosts call `register_site_setting!` the same way.
499    fn footer_fields() -> Vec<Widget> {
500        vec![
501            Widget::new(WidgetKind::Text, "site_name", "Site name").required(),
502            Widget::new(WidgetKind::Integer, "since", "Founded year"),
503            Widget::new(WidgetKind::Float, "rating", "Rating"),
504            Widget::new(WidgetKind::Boolean, "show_social", "Show social links"),
505            Widget::new(WidgetKind::MultiSelect, "networks", "Networks"),
506        ]
507    }
508    crate::register_site_setting!("__test_footer", "Test footer", footer_fields);
509
510    fn form(pairs: &[(&str, &str)]) -> HashMap<String, String> {
511        pairs
512            .iter()
513            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
514            .collect()
515    }
516
517    #[test]
518    fn schema_for_finds_registered_and_ignores_unknown() {
519        let s = schema_for("__test_footer").expect("registered schema");
520        assert_eq!(s.label, "Test footer");
521        assert_eq!((s.fields)().len(), 5);
522        assert!(schema_for("definitely-not-registered").is_none());
523        assert!(registered_schemas()
524            .iter()
525            .any(|s| s.scope == "__test_footer"));
526    }
527
528    #[test]
529    fn form_coerces_values_by_widget_kind() {
530        let fields = footer_fields();
531        // `show_social` checkbox present, CSRF + an unknown key present.
532        let f = form(&[
533            ("site_name", "Eugene Co"),
534            ("since", "2014"),
535            ("rating", "4.5"),
536            ("show_social", "on"),
537            ("networks", r#"["x","mastodon"]"#),
538            ("csrf_token", "tok"),
539            ("stray", "ignored"),
540        ]);
541        let v = value_json_from_form(&fields, &f);
542        assert_eq!(v["site_name"], serde_json::json!("Eugene Co"));
543        assert_eq!(v["since"], serde_json::json!(2014)); // integer, not "2014"
544        assert_eq!(v["rating"], serde_json::json!(4.5)); // float
545        assert_eq!(v["show_social"], serde_json::json!(true)); // checkbox present
546        assert_eq!(v["networks"], serde_json::json!(["x", "mastodon"])); // parsed array
547                                                                         // Keys outside the schema never leak into storage.
548        assert!(v.get("csrf_token").is_none());
549        assert!(v.get("stray").is_none());
550    }
551
552    #[test]
553    fn absent_checkbox_is_false_blank_number_dropped() {
554        let fields = footer_fields();
555        // No `show_social` key (unchecked) and an empty `since`.
556        let v = value_json_from_form(&fields, &form(&[("site_name", "X"), ("since", "")]));
557        assert_eq!(v["show_social"], serde_json::json!(false));
558        assert!(v.get("since").is_none()); // blank numeric → dropped
559    }
560
561    #[test]
562    fn unparseable_number_kept_as_string_not_lost() {
563        let fields = footer_fields();
564        let v = value_json_from_form(&fields, &form(&[("site_name", "X"), ("since", "MMXIV")]));
565        assert_eq!(v["since"], serde_json::json!("MMXIV"));
566    }
567
568    #[test]
569    fn prefill_round_trips_through_widget_value() {
570        let stored = serde_json::json!({
571            "site_name": "Eugene Co",
572            "since": 2014,
573            "show_social": true,
574            "networks": ["x", "mastodon"],
575        });
576        let widgets = prefill_widgets(footer_fields(), &stored);
577        let by_name = |n: &str| widgets.iter().find(|w| w.name == n).unwrap().value.clone();
578        assert_eq!(by_name("site_name"), "Eugene Co");
579        assert_eq!(by_name("since"), "2014"); // number → bare text
580        assert_eq!(by_name("show_social"), "on"); // truthy → checkbox checked
581        assert_eq!(by_name("networks"), r#"["x","mastodon"]"#); // array → JSON string
582    }
583
584    #[test]
585    fn missing_required_flags_blank_required_text_only() {
586        let fields = footer_fields();
587        // site_name required + blank → flagged; integer/bool not required.
588        let missing = missing_required(&fields, &form(&[("site_name", "  ")]));
589        assert_eq!(missing, vec!["Site name".to_owned()]);
590        // Provided → no complaint.
591        assert!(missing_required(&fields, &form(&[("site_name", "ok")])).is_empty());
592    }
593}
594
595#[cfg(test)]
596mod render_tests {
597    use super::*;
598    use std::collections::HashMap;
599    use tera::{Context, Tera};
600
601    fn fresh_tera() -> Tera {
602        let mut tera = Tera::default();
603        register_tera_function(&mut tera);
604        tera
605    }
606
607    fn render(tera: &Tera, src: &str) -> String {
608        let mut t = tera.clone();
609        t.add_raw_template("t.html", src).unwrap();
610        t.render("t.html", &Context::new()).unwrap()
611    }
612
613    #[test]
614    fn returns_null_when_nothing_installed() {
615        let tera = fresh_tera();
616        let out = render(
617            &tera,
618            r#"{% set v = site_setting(scope="footer") %}{% if v %}has{% else %}none{% endif %}"#,
619        );
620        assert_eq!(out, "none");
621    }
622
623    #[test]
624    fn resolves_known_scope_value_object() {
625        let mut m = HashMap::new();
626        m.insert(
627            "footer".to_owned(),
628            serde_json::json!({"site_name": "Eugene", "copyright": 2026}),
629        );
630        let _g = install(m);
631        let tera = fresh_tera();
632        // Tera only allows field-access on a NAMED variable, not on
633        // the result of a function call — assign once, then read.
634        let out = render(
635            &tera,
636            r#"{% set footer = site_setting(scope="footer") %}{{ footer.site_name }}-{{ footer.copyright }}"#,
637        );
638        assert_eq!(out, "Eugene-2026");
639    }
640
641    #[test]
642    fn missing_scope_returns_null() {
643        let mut m = HashMap::new();
644        m.insert("footer".to_owned(), serde_json::json!({"x": 1}));
645        let _g = install(m);
646        let tera = fresh_tera();
647        let out = render(
648            &tera,
649            r#"{% set v = site_setting(scope="missing") %}{% if v %}has{% else %}none{% endif %}"#,
650        );
651        assert_eq!(out, "none");
652    }
653
654    #[test]
655    fn empty_scope_arg_returns_null() {
656        let mut m = HashMap::new();
657        m.insert("footer".to_owned(), serde_json::json!({}));
658        let _g = install(m);
659        let tera = fresh_tera();
660        let out = render(
661            &tera,
662            r#"{% set v = site_setting(scope="") %}{% if v %}has{% else %}none{% endif %}"#,
663        );
664        assert_eq!(out, "none");
665    }
666
667    #[test]
668    fn guard_clears_thread_local() {
669        {
670            let mut m = HashMap::new();
671            m.insert("x".to_owned(), serde_json::json!({"v": 1}));
672            let _g = install(m);
673            let tera = fresh_tera();
674            assert_eq!(
675                render(&tera, r#"{% set s = site_setting(scope="x") %}{{ s.v }}"#,),
676                "1",
677            );
678        }
679        let tera = fresh_tera();
680        let out = render(
681            &tera,
682            r#"{% set v = site_setting(scope="x") %}{% if v %}has{% else %}none{% endif %}"#,
683        );
684        assert_eq!(out, "none");
685    }
686}