Skip to main content

rustango_cms/
page_url.rs

1//! `pageurl(id=N)` Tera helper — resolve a `cms_page` id to its
2//! public URL at render time.
3//!
4//! A `pageurl` lookup handles the common
5//! case of a `ForeignKey(Page)` on an extension row (CTA targets,
6//! related-page choosers, etc.) — the template asks for the URL,
7//! the CMS walks the page tree. Concretely, the public render
8//! pipeline scans the extension dict for `*_id` fields whose values
9//! resolve to a `cms_page` row, pre-fetches the rows in a single
10//! batch query, and exposes both a `_pages_by_id` ctx map AND a
11//! `pageurl(id=…)` Tera function (plus a `| pageurl` filter) so
12//! templates can write `{{ pageurl(id=extension.hero_cta_page_id) }}`.
13//!
14//! Tera 1.x doesn't pass the global context into function / filter
15//! args, so we stash the resolved map in a thread-local that
16//! [`render::render_inner`](mod@crate::render) sets right before
17//! `tera.render(…)` runs and clears the moment render returns
18//! (RAII via [`PageUrlGuard`]). Tera's `render` is fully sync, so the
19//! thread-local survives the whole call without leaking across
20//! requests scheduled on the same tokio worker.
21//!
22//! Pre-fetch is capped at [`MAX_PREFETCH_IDS`] lookups per page
23//! render. Above the cap the function still resolves ids that DID
24//! make it into the map; the rest fall back to `"#"`. The cap is
25//! deliberately small so a malformed extension JSON (or a future
26//! N-to-M field) can't fan a single page request out into hundreds
27//! of point lookups.
28//!
29//! Missing / unresolvable / 0 ids return `"#"` so templates can drop
30//! the value straight into an `href` attribute without a guard.
31
32use std::cell::RefCell;
33use std::collections::HashMap;
34use std::sync::Arc;
35
36use rustango::core::Column as _;
37use rustango::sql::FetcherPool as _;
38use tera::{Filter, Function, Tera, Value};
39
40use crate::page::Page;
41
42/// Cap on the number of `*_id` fields the prefetch walker resolves
43/// per page render. See module docs for the rationale.
44pub const MAX_PREFETCH_IDS: usize = 16;
45
46thread_local! {
47    /// Per-thread `page_id → url_path` map. Lives only for the
48    /// duration of a single `tera.render` call, installed and cleared
49    /// via [`PageUrlGuard`].
50    static CURRENT_PAGES_BY_ID: RefCell<Option<Arc<HashMap<i64, String>>>>
51        = const { RefCell::new(None) };
52
53    /// Per-thread public mount prefix (`""` at root, `"/p"` for a
54    /// prefixed mount) — installed by the render pipeline so
55    /// [`page_href`](self) can emit fully-qualified links. Cleared via
56    /// [`UrlPrefixGuard`].
57    static CURRENT_URL_PREFIX: RefCell<String> = const { RefCell::new(String::new()) };
58    /// The serving site's root path, stripped from emitted links.
59    static CURRENT_SITE_PREFIX: RefCell<String> = const { RefCell::new(String::new()) };
60}
61
62/// RAII guard. While in scope the thread-local map is set; on drop
63/// it's cleared. Returned by [`install`]; callers MUST keep it alive
64/// across `tera.render(…)` and let it drop right after.
65#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
66pub struct PageUrlGuard {
67    // Field exists so the guard isn't ZST and can be `must_use`.
68    _priv: (),
69}
70
71impl Drop for PageUrlGuard {
72    fn drop(&mut self) {
73        CURRENT_PAGES_BY_ID.with(|cell| {
74            *cell.borrow_mut() = None;
75        });
76    }
77}
78
79/// Install `pages_by_id` for the duration of the returned guard.
80/// Subsequent calls to `pageurl(id=N)` on this thread resolve N
81/// against the installed map.
82pub fn install(pages_by_id: HashMap<i64, String>) -> PageUrlGuard {
83    CURRENT_PAGES_BY_ID.with(|cell| {
84        *cell.borrow_mut() = Some(Arc::new(pages_by_id));
85    });
86    PageUrlGuard { _priv: () }
87}
88
89/// Resolve a page id against the currently-installed map. Returns
90/// `None` when nothing is installed, when `id <= 0`, or when the
91/// page wasn't pre-fetched. Used by [`crate::richtext`] to
92/// rewrite `<a linktype="page" id="N">` anchors against the same
93/// map the `pageurl(id=…)` Tera function reads.
94#[must_use]
95pub fn lookup(id: i64) -> Option<String> {
96    if id <= 0 {
97        return None;
98    }
99    CURRENT_PAGES_BY_ID.with(|cell| cell.borrow().as_ref().and_then(|m| m.get(&id).cloned()))
100}
101
102/// RAII guard for the render-scoped `url_prefix`. Mirrors
103/// [`PageUrlGuard`]; clears the prefix on drop.
104#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
105pub struct UrlPrefixGuard {
106    _priv: (),
107}
108
109impl Drop for UrlPrefixGuard {
110    fn drop(&mut self) {
111        CURRENT_URL_PREFIX.with(|cell| cell.borrow_mut().clear());
112    }
113}
114
115/// RAII guard for the render-scoped site prefix.
116#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
117pub struct SitePrefixGuard {
118    _priv: (),
119}
120impl Drop for SitePrefixGuard {
121    fn drop(&mut self) {
122        CURRENT_SITE_PREFIX.with(|cell| cell.borrow_mut().clear());
123    }
124}
125
126/// Install the serving site's root path, so links to pages inside that
127/// site are emitted relative to it.
128///
129/// The inverse of the mount prefix, and applied first: `url_path` is
130/// stored tenant-absolute (`/site-b/about`), while a visitor on
131/// `siteb.com` must see `/about`. A page outside the site keeps its
132/// absolute path — see [`crate::site::to_public_path`].
133pub fn install_site_prefix(prefix: &str) -> SitePrefixGuard {
134    CURRENT_SITE_PREFIX.with(|cell| {
135        *cell.borrow_mut() = prefix.to_owned();
136    });
137    SitePrefixGuard { _priv: () }
138}
139
140fn current_site_prefix() -> String {
141    CURRENT_SITE_PREFIX.with(|cell| cell.borrow().clone())
142}
143
144/// Install the public mount `prefix` for the duration of the returned
145/// guard so [`page_href`](self) emits `{prefix}{url_path}` links. The
146/// render pipeline installs this alongside the `pageurl` map.
147pub fn install_url_prefix(prefix: &str) -> UrlPrefixGuard {
148    CURRENT_URL_PREFIX.with(|cell| {
149        *cell.borrow_mut() = prefix.to_owned();
150    });
151    UrlPrefixGuard { _priv: () }
152}
153
154fn current_url_prefix() -> String {
155    CURRENT_URL_PREFIX.with(|cell| cell.borrow().clone())
156}
157
158/// Register the `pageurl` Tera function and the `| pageurl` filter
159/// on `tera`. Call once at Tera setup — wired from
160/// [`crate::urls::register_tera_helpers`] so host apps that use the
161/// bundled `register_templates` get it for free.
162///
163/// Both forms are marked `is_safe = true`: the URL is read from the
164/// `cms_page.url_path` column maintained by `tree_ops`, which is
165/// CMS-controlled, not user input, so the output can flow into
166/// `href=…` unescaped.
167pub fn register_tera_function(tera: &mut Tera) {
168    tera.register_function("pageurl", PageurlFn);
169    tera.register_filter("pageurl", PageurlFilter);
170    // #NNN — `page_href`: the one-call, prefix-aware page→link helper.
171    // Function form `page_href(page=child)` / `page_href(id=42)`, filter
172    // form `{{ child | page_href }}`. Unlike `pageurl` (bare url_path, id
173    // only) it accepts a page-shaped object *and* prepends the mount
174    // `url_prefix`, so a `children`/`ancestors` loop links correctly for
175    // deep trees without the template hand-building `url_prefix ~ slug`.
176    tera.register_function("page_href", PageHrefFn);
177    tera.register_filter("page_href", PageHrefFilter);
178    // #members — `page_link`: emit a ready-made `<a href>title</a>` for a
179    // page-shaped object (or id), prefix-aware, title HTML-escaped.
180    // Function `page_link(page=child, class="nav")` / filter
181    // `{{ child | page_link }}`. Pair with `can_view` to hide protected
182    // links: `{% if child | can_view %}{{ child | page_link }}{% endif %}`.
183    tera.register_function("page_link", PageLinkFn);
184    tera.register_filter("page_link", PageLinkFilter);
185}
186
187struct PageLinkFn;
188
189impl Function for PageLinkFn {
190    fn call(&self, args: &HashMap<String, Value>) -> tera::Result<Value> {
191        let (href, title) = match args.get("page") {
192            Some(page) => (href_from_value(page), title_from_value(page)),
193            None => {
194                let id = args.get("id").and_then(read_id);
195                (href_from_id(id), None)
196            }
197        };
198        let class = args.get("class").and_then(Value::as_str);
199        Ok(Value::String(anchor(&href, title.as_deref(), class)))
200    }
201    fn is_safe(&self) -> bool {
202        true
203    }
204}
205
206struct PageLinkFilter;
207
208impl Filter for PageLinkFilter {
209    fn filter(&self, value: &Value, args: &HashMap<String, Value>) -> tera::Result<Value> {
210        let class = args.get("class").and_then(Value::as_str);
211        Ok(Value::String(anchor(
212            &href_from_value(value),
213            title_from_value(value).as_deref(),
214            class,
215        )))
216    }
217    fn is_safe(&self) -> bool {
218        true
219    }
220}
221
222/// Read a page-shaped value's title (falls back to the href text when
223/// absent so the anchor is never empty).
224fn title_from_value(value: &Value) -> Option<String> {
225    value
226        .get("title")
227        .and_then(Value::as_str)
228        .filter(|s| !s.is_empty())
229        .map(str::to_owned)
230}
231
232/// Build a safe `<a>` element. `href` is CMS-controlled (`url_path`);
233/// `title` is page-authored text, so it's HTML-escaped.
234fn anchor(href: &str, title: Option<&str>, class: Option<&str>) -> String {
235    let label = escape_html(title.unwrap_or(href));
236    match class {
237        Some(c) if !c.is_empty() => {
238            format!(r#"<a class="{}" href="{href}">{label}</a>"#, escape_html(c))
239        }
240        _ => format!(r#"<a href="{href}">{label}</a>"#),
241    }
242}
243
244/// Minimal HTML-attribute/text escaper for the `page_link` label +
245/// class (the helper is `is_safe`, so it must escape its own dynamic
246/// text). `href` comes from the CMS-maintained `url_path` and is left
247/// verbatim, matching `pageurl` / `page_href`.
248fn escape_html(s: &str) -> String {
249    let mut out = String::with_capacity(s.len());
250    for c in s.chars() {
251        match c {
252            '&' => out.push_str("&amp;"),
253            '<' => out.push_str("&lt;"),
254            '>' => out.push_str("&gt;"),
255            '"' => out.push_str("&quot;"),
256            '\'' => out.push_str("&#x27;"),
257            _ => out.push(c),
258        }
259    }
260    out
261}
262
263struct PageHrefFn;
264
265impl Function for PageHrefFn {
266    fn call(&self, args: &HashMap<String, Value>) -> tera::Result<Value> {
267        // `page=<object>` wins; else `id=<int>`.
268        let href = match args.get("page") {
269            Some(page) => href_from_value(page),
270            None => href_from_id(args.get("id").and_then(read_id)),
271        };
272        Ok(Value::String(href))
273    }
274    fn is_safe(&self) -> bool {
275        true
276    }
277}
278
279struct PageHrefFilter;
280
281impl Filter for PageHrefFilter {
282    fn filter(&self, value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
283        Ok(Value::String(href_from_value(value)))
284    }
285    fn is_safe(&self) -> bool {
286        true
287    }
288}
289
290/// Build a page href from a Tera value that is either a page-shaped
291/// object (has a `url_path`) or a bare id (i64 / stringified int).
292fn href_from_value(value: &Value) -> String {
293    if let Some(url_path) = value.get("url_path").and_then(Value::as_str) {
294        return with_prefix(url_path);
295    }
296    // Not an object with url_path — treat it as an id reference.
297    href_from_id(read_id(value))
298}
299
300/// Build a page href from a page id resolved against the installed
301/// `pageurl` map. Unresolved / missing → `"#"`.
302fn href_from_id(id: Option<i64>) -> String {
303    match id.and_then(lookup) {
304        Some(url_path) => with_prefix(&url_path),
305        None => "#".to_owned(),
306    }
307}
308
309/// Prepend the render-scoped mount prefix to a `url_path`. An empty
310/// `url_path` (root/unset) yields `{prefix}/` so the link is never bare.
311fn with_prefix(url_path: &str) -> String {
312    let prefix = current_url_prefix();
313    // Site first, mount second. `url_path` is tenant-absolute, so the
314    // site's root is stripped before the mount prefix is prepended —
315    // the other order would try to strip `/blog/site-b` from a path that
316    // only ever contained `/site-b`.
317    let site = current_site_prefix();
318    let url_path = crate::site::to_public_path(&site, url_path);
319    if url_path.is_empty() {
320        format!("{prefix}/")
321    } else {
322        format!("{prefix}{url_path}")
323    }
324}
325
326struct PageurlFn;
327
328impl Function for PageurlFn {
329    fn call(&self, args: &HashMap<String, Value>) -> tera::Result<Value> {
330        let id = args.get("id").and_then(read_id);
331        // Same href as `page_href`: mount prefix + the site's public path (#640).
332        Ok(Value::String(href_from_id(id)))
333    }
334    fn is_safe(&self) -> bool {
335        true
336    }
337}
338
339struct PageurlFilter;
340
341impl Filter for PageurlFilter {
342    fn filter(&self, value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
343        Ok(Value::String(href_from_id(read_id(value))))
344    }
345    fn is_safe(&self) -> bool {
346        true
347    }
348}
349
350/// Accept i64 (post-save shape) and stringified ints (preview-form
351/// shape — HTML form values come through as strings). `null` and
352/// empty strings yield `None`, which the caller turns into `"#"`.
353fn read_id(v: &Value) -> Option<i64> {
354    if v.is_null() {
355        return None;
356    }
357    if let Some(n) = v.as_i64() {
358        return Some(n);
359    }
360    v.as_str()
361        .map(str::trim)
362        .filter(|s| !s.is_empty())
363        .and_then(|s| s.parse::<i64>().ok())
364}
365
366/// Scan the extension JSON for top-level fields whose name ends with
367/// `_id` and value is an i64, batch-fetch the matching `cms_page`
368/// rows, and return a `page_id → url_path` map. Bounded at
369/// [`MAX_PREFETCH_IDS`] lookups per call — see the module docs.
370///
371/// Returns an empty map on any error (driver failure, no candidate
372/// ids, etc.); the rendered template falls back to `"#"` and the
373/// page still renders. The error is logged.
374///
375/// # Errors
376/// None — failures degrade to an empty map.
377pub async fn prefetch_for_extension(
378    extension: &serde_json::Value,
379    pool: &rustango::sql::Pool,
380) -> HashMap<i64, String> {
381    let mut ids: Vec<i64> = candidate_ids(extension);
382    if ids.is_empty() {
383        return HashMap::new();
384    }
385    // Stable dedupe — same id referenced under multiple `*_id` fields
386    // still incurs one row in the IN list.
387    ids.sort_unstable();
388    ids.dedup();
389    if ids.len() > MAX_PREFETCH_IDS {
390        tracing::debug!(
391            target: "rustango_cms::page_url",
392            count = ids.len(),
393            cap = MAX_PREFETCH_IDS,
394            "extension referenced more *_id fields than the prefetch cap; tail truncated",
395        );
396        ids.truncate(MAX_PREFETCH_IDS);
397    }
398    match Page::objects()
399        .where_(Page::id.is_in(ids))
400        .fetch(pool)
401        .await
402    {
403        Ok(rows) => rows
404            .into_iter()
405            .filter_map(|p| p.id.get().copied().map(|id| (id, p.url_path)))
406            .collect(),
407        Err(e) => {
408            tracing::warn!(
409                target: "rustango_cms::page_url",
410                error = %e,
411                "pageurl prefetch failed; templates will see '#'",
412            );
413            HashMap::new()
414        }
415    }
416}
417
418/// Pull every `*_id` field off the top-level extension object and
419/// return their i64 values (positive only). Stringified ints are
420/// accepted alongside raw numbers — extension JSON for an unsaved
421/// preview carries form-shape strings.
422///
423/// The walk is intentionally shallow: nested objects / arrays aren't
424/// descended. Nested chooser refs (stream blocks, repeat blocks) are
425/// already enriched by
426/// [`crate::block::tera_helpers::enrich_chooser_refs_async`] with
427/// `value._url`, which is a separate channel.
428fn candidate_ids(extension: &serde_json::Value) -> Vec<i64> {
429    let Some(obj) = extension.as_object() else {
430        return Vec::new();
431    };
432    obj.iter()
433        .filter(|(k, _)| k.ends_with("_id"))
434        .filter_map(|(_, v)| read_id(v))
435        .filter(|n| *n > 0)
436        .collect()
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442    use serde_json::json;
443    use tera::{Context, Tera};
444
445    fn fresh_tera() -> Tera {
446        let mut tera = Tera::default();
447        register_tera_function(&mut tera);
448        tera
449    }
450
451    #[test]
452    fn function_resolves_known_id() {
453        let mut map = HashMap::new();
454        map.insert(42i64, "/about".to_owned());
455        let _guard = install(map);
456
457        let tera = fresh_tera();
458        let mut t = tera.clone();
459        t.add_raw_template("t.html", "{{ pageurl(id=42) }}")
460            .unwrap();
461        let out = t.render("t.html", &Context::new()).unwrap();
462        assert_eq!(out, "/about");
463    }
464
465    #[test]
466    fn function_returns_hash_for_unknown_id() {
467        let _guard = install(HashMap::new());
468        let tera = fresh_tera();
469        let mut t = tera.clone();
470        t.add_raw_template("t.html", "{{ pageurl(id=999) }}")
471            .unwrap();
472        let out = t.render("t.html", &Context::new()).unwrap();
473        assert_eq!(out, "#");
474    }
475
476    #[test]
477    fn function_returns_hash_for_zero_and_negative() {
478        let mut map = HashMap::new();
479        map.insert(0i64, "/should-not-leak".to_owned());
480        let _guard = install(map);
481        let tera = fresh_tera();
482        let mut t = tera.clone();
483        t.add_raw_template("z.html", "{{ pageurl(id=0) }}").unwrap();
484        t.add_raw_template("n.html", "{{ pageurl(id=-3) }}")
485            .unwrap();
486        assert_eq!(t.render("z.html", &Context::new()).unwrap(), "#");
487        assert_eq!(t.render("n.html", &Context::new()).unwrap(), "#");
488    }
489
490    #[test]
491    fn function_accepts_stringified_id() {
492        // Preview-form values come through as JSON strings.
493        let mut map = HashMap::new();
494        map.insert(7i64, "/team".to_owned());
495        let _guard = install(map);
496        let tera = fresh_tera();
497        let mut t = tera.clone();
498        t.add_raw_template("t.html", r#"{{ pageurl(id="7") }}"#)
499            .unwrap();
500        assert_eq!(t.render("t.html", &Context::new()).unwrap(), "/team");
501    }
502
503    #[test]
504    fn filter_resolves_known_id() {
505        let mut map = HashMap::new();
506        map.insert(3i64, "/blog".to_owned());
507        let _guard = install(map);
508        let tera = fresh_tera();
509        let mut t = tera.clone();
510        let mut ctx = Context::new();
511        ctx.insert("hero_cta_page_id", &3i64);
512        t.add_raw_template("t.html", "{{ hero_cta_page_id | pageurl }}")
513            .unwrap();
514        assert_eq!(t.render("t.html", &ctx).unwrap(), "/blog");
515    }
516
517    #[test]
518    fn filter_returns_hash_for_null() {
519        let _guard = install(HashMap::new());
520        let tera = fresh_tera();
521        let mut t = tera.clone();
522        let mut ctx = Context::new();
523        ctx.insert("maybe_id", &serde_json::Value::Null);
524        t.add_raw_template("t.html", "{{ maybe_id | pageurl }}")
525            .unwrap();
526        assert_eq!(t.render("t.html", &ctx).unwrap(), "#");
527    }
528
529    #[test]
530    fn guard_clears_thread_local() {
531        {
532            let mut map = HashMap::new();
533            map.insert(1i64, "/x".to_owned());
534            let _g = install(map);
535            assert_eq!(href_from_id(Some(1)), "/x");
536        }
537        assert_eq!(href_from_id(Some(1)), "#");
538    }
539
540    #[test]
541    fn candidate_ids_picks_up_underscore_id_fields() {
542        let ext = json!({
543            "title": "Home",
544            "hero_cta_page_id": 4,
545            "related_page_id": "9",
546            "irrelevant": 1,
547            "body_stream": [{"type": "page_chooser", "value": {"page_id": 99}}],
548            "expire_at_id": null,
549        });
550        let mut ids = candidate_ids(&ext);
551        ids.sort_unstable();
552        assert_eq!(ids, vec![4, 9]);
553    }
554
555    #[test]
556    fn candidate_ids_ignores_non_object_extension() {
557        assert!(candidate_ids(&serde_json::Value::Null).is_empty());
558        assert!(candidate_ids(&json!([1, 2, 3])).is_empty());
559        assert!(candidate_ids(&json!("string")).is_empty());
560    }
561
562    #[test]
563    fn candidate_ids_skips_non_positive() {
564        let ext = json!({"foo_id": 0, "bar_id": -1, "baz_id": 5});
565        let ids = candidate_ids(&ext);
566        assert_eq!(ids, vec![5]);
567    }
568
569    // ---- page_href ----
570
571    fn render_expr(expr: &str, ctx: &Context) -> String {
572        let mut t = fresh_tera();
573        t.add_raw_template("t.html", expr).unwrap();
574        t.render("t.html", ctx).unwrap()
575    }
576
577    #[test]
578    fn page_href_filter_uses_full_url_path_not_leaf_slug() {
579        // A grandchild at /about/team must link to the FULL path, not /team.
580        let _prefix = install_url_prefix("");
581        let mut ctx = Context::new();
582        ctx.insert(
583            "child",
584            &json!({ "slug": "team", "url_path": "/about/team", "title": "Team" }),
585        );
586        assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/about/team");
587    }
588
589    #[test]
590    fn page_href_prepends_mount_prefix() {
591        let _prefix = install_url_prefix("/p");
592        let mut ctx = Context::new();
593        ctx.insert("child", &json!({ "url_path": "/about" }));
594        assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/p/about");
595    }
596
597    #[test]
598    fn page_href_function_form_and_id_resolution() {
599        let mut map = HashMap::new();
600        map.insert(42i64, "/about".to_owned());
601        let _guard = install(map);
602        let _prefix = install_url_prefix("/p");
603        // object form
604        let mut ctx = Context::new();
605        ctx.insert("anc", &json!({ "url_path": "/about/team" }));
606        assert_eq!(
607            render_expr("{{ page_href(page=anc) }}", &ctx),
608            "/p/about/team"
609        );
610        // id form resolves via the installed map + prefix
611        assert_eq!(
612            render_expr("{{ page_href(id=42) }}", &Context::new()),
613            "/p/about"
614        );
615    }
616
617    #[test]
618    fn page_href_missing_and_empty() {
619        let _guard = install(HashMap::new());
620        let _prefix = install_url_prefix("");
621        // unresolved id → "#"
622        assert_eq!(render_expr("{{ page_href(id=999) }}", &Context::new()), "#");
623        // object with empty url_path (root) → "{prefix}/"
624        let mut ctx = Context::new();
625        ctx.insert("root", &json!({ "url_path": "" }));
626        assert_eq!(render_expr("{{ root | page_href }}", &ctx), "/");
627    }
628
629    #[test]
630    fn page_href_prefix_guard_clears() {
631        {
632            let _p = install_url_prefix("/p");
633            assert_eq!(current_url_prefix(), "/p");
634        }
635        assert_eq!(current_url_prefix(), "");
636    }
637
638
639    /// The composition that matters: a site-relative link, emitted from a
640    /// CMS mounted under a path prefix. Site strip happens first.
641    #[test]
642    fn site_prefix_is_stripped_before_the_mount_prefix_is_added() {
643        let _mount = install_url_prefix("/p");
644        let _site = install_site_prefix("/site-b");
645        let mut ctx = Context::new();
646        ctx.insert("child", &json!({ "url_path": "/site-b/about" }));
647        assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/p/about");
648    }
649
650    #[test]
651    fn the_site_root_itself_links_to_the_mount_root() {
652        let _mount = install_url_prefix("");
653        let _site = install_site_prefix("/site-b");
654        let mut ctx = Context::new();
655        ctx.insert("child", &json!({ "url_path": "/site-b" }));
656        assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/");
657    }
658
659    /// A page on a different site must NOT be rewritten — an honest link
660    /// elsewhere beats a mangled one that 404s.
661    #[test]
662    fn a_page_outside_the_site_keeps_its_absolute_path() {
663        let _mount = install_url_prefix("");
664        let _site = install_site_prefix("/site-b");
665        let mut ctx = Context::new();
666        ctx.insert("child", &json!({ "url_path": "/other/page" }));
667        assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/other/page");
668    }
669
670    /// With no site installed the behaviour is exactly what it was, which
671    /// is what keeps every existing single-site deployment unchanged.
672    #[test]
673    fn no_site_prefix_means_unchanged_behaviour() {
674        let _mount = install_url_prefix("/p");
675        let mut ctx = Context::new();
676        ctx.insert("child", &json!({ "url_path": "/about" }));
677        assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/p/about");
678    }
679
680    /// `pageurl` emits the same href as `page_href`.
681    #[test]
682    fn pageurl_strips_the_site_and_adds_the_mount_prefix() {
683        let _mount = install_url_prefix("/p");
684        let _site = install_site_prefix("/site-b");
685        let _pages = install(HashMap::from([(4i64, "/site-b/about".to_owned())]));
686        let ctx = Context::new();
687        assert_eq!(render_expr("{{ pageurl(id=4) }}", &ctx), "/p/about");
688        assert_eq!(render_expr("{{ 4 | pageurl }}", &ctx), "/p/about");
689    }
690}