Skip to main content

rustango_cms/
render.rs

1//! Render a resolved [`Page`] through Tera.
2//!
3//! The flow:
4//!
5//! 1. Look up the [`PageType`] row via `page.page_type_id`.
6//! 2. Find the registered [`PageTypeHandler`](crate::page_type::PageTypeHandler) by `type_name`.
7//! 3. Ask the handler for its typed extension as JSON
8//!    (`load_extension`).
9//! 4. Build a Tera context with `page` / `page_type` / `extension`
10//!    / `children` / `ancestors` / `breadcrumbs`.
11//! 5. Render the page's own `template_override` when it names a
12//!    template that exists, else `page_type.default_template`
13//!    (see `pick_template`).
14
15use axum::http::StatusCode;
16use axum::response::{Html, IntoResponse, Response};
17use rustango::core::Column as _;
18use rustango::extractors::Tenant;
19use rustango::sql::FetcherPool as _;
20use tera::{Context, Tera};
21
22use crate::page::Page;
23use crate::page_type::find_handler;
24use crate::page_type_model::PageType;
25
26/// Render `page` to an HTTP response. On any failure (missing
27/// page-type row, missing handler, template error) returns a
28/// 500/404 response with a short diagnostic body.
29///
30/// `url_prefix` is the mount prefix the public CMS is served under
31/// (e.g. `""` for root, `"/p"` for `router_at("/p", _)`). It is
32/// injected into the Tera context as `url_prefix`, but prefer the
33/// `page_href` helper for links — `{{ child | page_href }}` /
34/// `{{ page_href(page=ancestor) }}` — which prepends the prefix to the
35/// page's full `url_path`. Do NOT build links as
36/// `{{ url_prefix }}/{{ ancestor.slug }}` — the leaf slug alone breaks
37/// for any page deeper than one level (a grandchild `/a/b` → `/b`).
38pub async fn render(
39    t: &Tenant,
40    tera: &Tera,
41    page: &Page,
42    url_prefix: &str,
43    // The serving site's root path, stripped from emitted links. Empty
44    // for a single-site tenant, which is every existing one.
45    site_prefix: &str,
46    locale_code: Option<&str>,
47    viewer: Option<&rustango::tenancy::auth::User>,
48    cache: Option<(&rustango::cache::BoxedCache, std::time::Duration)>,
49) -> Response {
50    render_negotiated(
51        t,
52        tera,
53        page,
54        url_prefix,
55        site_prefix,
56        locale_code,
57        viewer,
58        crate::page_view::Accept::Html,
59        cache,
60    )
61    .await
62}
63
64/// [`render`], plus the client's media-type preference.
65///
66/// Only page types that opt into a JSON view read `accept` at all — see
67/// [`crate::page_view`]. `render` is the `Accept::Html` case and stays
68/// source-compatible for every existing caller, including the admin's
69/// own preview route.
70#[allow(clippy::too_many_arguments)]
71pub async fn render_negotiated(
72    t: &Tenant,
73    tera: &Tera,
74    page: &Page,
75    url_prefix: &str,
76    // The serving site's root path, stripped from emitted links. Empty
77    // for a single-site tenant, which is every existing one.
78    site_prefix: &str,
79    locale_code: Option<&str>,
80    viewer: Option<&rustango::tenancy::auth::User>,
81    accept: crate::page_view::Accept,
82    cache: Option<(&rustango::cache::BoxedCache, std::time::Duration)>,
83) -> Response {
84    render_inner(
85        t,
86        tera,
87        page,
88        url_prefix,
89        site_prefix,
90        locale_code,
91        viewer,
92        None,
93        None,
94        accept,
95        false,
96        cache,
97    )
98    .await
99}
100
101/// Render `page` as a routable-page hit. The matched route's
102/// name + named capture groups are exposed to the template as
103/// `route_name` and `route_captures`; the handler's
104/// `route_context` override gets a chance to inject additional ctx
105/// before the framework keys are stamped.
106#[allow(clippy::too_many_arguments)]
107pub async fn render_with_route(
108    t: &Tenant,
109    tera: &Tera,
110    page: &Page,
111    url_prefix: &str,
112    // The serving site's root path, stripped from emitted links. Empty
113    // for a single-site tenant, which is every existing one.
114    site_prefix: &str,
115    locale_code: Option<&str>,
116    viewer: Option<&rustango::tenancy::auth::User>,
117    route_match: &crate::routable::RouteMatch,
118    accept: crate::page_view::Accept,
119    cache: Option<(&rustango::cache::BoxedCache, std::time::Duration)>,
120) -> Response {
121    render_inner(
122        t,
123        tera,
124        page,
125        url_prefix,
126        site_prefix,
127        locale_code,
128        viewer,
129        None,
130        Some(route_match),
131        accept,
132        false,
133        cache,
134    )
135    .await
136}
137
138/// Most grandchild ids an index page reads for its translations; cards
139/// past it show in the default language.
140const MAX_GRANDCHILD_IDS: i64 = 500;
141
142/// Ids of the children of `children`, at most
143/// [`MAX_GRANDCHILD_IDS`] of them.
144async fn grandchild_ids(pool: &rustango::sql::Pool, children: &[Page]) -> Vec<i64> {
145    use rustango::core::Column as _;
146    let child_ids: Vec<i64> = children.iter().filter_map(|p| p.id.get().copied()).collect();
147    if child_ids.is_empty() {
148        return Vec::new();
149    }
150    Page::objects()
151        .where_(Page::parent_id.is_in(child_ids))
152        .order_by(&[("id", false)])
153        .limit(MAX_GRANDCHILD_IDS)
154        .values_list_flat("id")
155        .fetch::<i64>(pool)
156        .await
157        .unwrap_or_else(|e| {
158            tracing::warn!(target: "rustango_cms::render", error = %e, "grandchild lookup failed");
159            Vec::new()
160        })
161}
162
163/// Render `page` using virtual extension data drawn from a posted
164/// form `HashMap` instead of the persisted row. The page row itself
165/// is still rendered verbatim, so callers should pre-overlay the
166/// form's canonical fields onto the `Page` before calling.
167///
168/// Powers the "preview unsaved changes" iframe in the editor: the
169/// admin's edit form POSTs its current state to a preview endpoint
170/// that builds a virtual `Page` + delegates here. Nothing is
171/// persisted.
172pub async fn render_preview(
173    t: &Tenant,
174    tera: &Tera,
175    page: &Page,
176    url_prefix: &str,
177    // No site rewriting in preview: the editor works in tenant-absolute
178    // paths, and a preview that silently re-based its links would not be
179    // showing the page the visitor gets.
180    site_prefix: &str,
181    locale_code: Option<&str>,
182    form: &std::collections::HashMap<String, String>,
183    accept: crate::page_view::Accept,
184    force_json: bool,
185) -> Response {
186    // Preview always renders fresh — never serve a cached menu fragment
187    // (the editor may be previewing unsaved tree/menu changes). Previews
188    // are admin-only, so menus show every item (viewer = None).
189    render_inner(
190        t,
191        tera,
192        page,
193        url_prefix,
194        site_prefix,
195        locale_code,
196        None,
197        Some(form),
198        None,
199        accept,
200        force_json,
201        None,
202    )
203    .await
204}
205
206#[allow(clippy::too_many_arguments)]
207async fn render_inner(
208    t: &Tenant,
209    tera: &Tera,
210    page: &Page,
211    url_prefix: &str,
212    // The serving site's root path, stripped from emitted links. Empty
213    // for a single-site tenant, which is every existing one.
214    site_prefix: &str,
215    locale_code: Option<&str>,
216    viewer: Option<&rustango::tenancy::auth::User>,
217    preview_form: Option<&std::collections::HashMap<String, String>>,
218    route_match: Option<&crate::routable::RouteMatch>,
219    accept: crate::page_view::Accept,
220    // Serialize regardless of the type's declared `view_mode`. Set
221    // **only** by the admin preview, where an authenticated editor has
222    // explicitly asked to see a page's API shape. The public path never
223    // sets it: letting `Accept` alone force JSON would give every
224    // `auto` page a JSON representation it never opted into.
225    force_json: bool,
226    cache: Option<(&rustango::cache::BoxedCache, std::time::Duration)>,
227) -> Response {
228    // #401 — take the language-switcher entries the public handler
229    // stashed just before polling this future (see
230    // `language_switcher::stash_pending`). Read here, before the first
231    // `.await`, so it runs on the caller's thread and becomes a plain
232    // local that travels with the future; it's re-installed in the
233    // await-free block below so the thread-local lands on the thread
234    // that runs `tera.render`, immune to tokio's thread-hops.
235    let pending_switcher = crate::language_switcher::take_pending();
236    // The request origin the public handler stashed (see
237    // `meta_tags::stash_site_origin`) — read here, before the first `.await`.
238    let site_origin = crate::meta_tags::take_site_origin().unwrap_or_default();
239    // #75 — alias resolution. When the row points at a source page,
240    // render the source's content (title, page_type, extension data,
241    // SEO, status, theme) while keeping the alias's URL-shape fields
242    // (id, slug, path, url_path, parent_id). That way the rendered
243    // body looks like the source but the URL stays the alias's.
244    //
245    // `extension_page_id` is the id to pass to the page-type
246    // handler's `load_extension`. For non-aliases it's the page's
247    // own id; for aliases it's the source's id (extension data is
248    // shared with the source).
249    let source_id_for_alias: Option<i64> = page.alias_of;
250    // `alias_owned` holds the hybrid Page for the alias path so the
251    // `&Page` returned by the if-expression has a stable owner. The
252    // initial `None` is overwritten before any read on the alias
253    // branch and never touched on the non-alias branch — silence
254    // the unused-assignment lint inline (the binding pattern is
255    // required for lifetime extension).
256    #[allow(unused_assignments)]
257    let mut alias_owned: Option<Page> = None;
258    // #395 — for an alias the canonical URL points at the SOURCE page's
259    // url_path (aliases are duplicate content of the source); captured
260    // from the source row below. `None` for non-aliases → self-canonical.
261    let mut canonical_source_path: Option<String> = None;
262    let page: &Page = if let Some(source_id) = source_id_for_alias {
263        use rustango::core::Column as _;
264        use rustango::sql::FetcherPool as _;
265        match Page::objects()
266            .where_(Page::id.eq(source_id))
267            .fetch(t.pool())
268            .await
269        {
270            Ok(rows) => match rows.into_iter().next() {
271                Some(src) => {
272                    // #395 — canonical points at the source page for aliases.
273                    canonical_source_path = Some(src.url_path.clone());
274                    alias_owned = Some(crate::page::alias_hybrid(page, &src));
275                    alias_owned.as_ref().unwrap()
276                }
277                None => {
278                    tracing::warn!(
279                        target: "rustango_cms::render",
280                        alias_id = ?page.id.get().copied(),
281                        source_id,
282                        "alias source missing — rendering alias row verbatim"
283                    );
284                    page
285                }
286            },
287            Err(e) => {
288                tracing::warn!(target: "rustango_cms::render", error = %e, "alias source fetch failed");
289                page
290            }
291        }
292    } else {
293        page
294    };
295    let extension_page_id: i64 = source_id_for_alias
296        .or_else(|| page.id.get().copied())
297        .unwrap_or_default();
298
299    // #395 — canonical URL: the source's path for aliases, else this
300    // page's own path (locale variants self-canonical; hreflang annotates
301    // the alternates). Relative to the public mount, consistent with the
302    // other URLs the renderer emits.
303    // #640 — on a hostname-mapped site, the site root's prefix is stripped
304    // like every other emitted link.
305    let canonical_url = format!(
306        "{url_prefix}{}",
307        crate::site::to_public_path(
308            site_prefix,
309            canonical_source_path
310                .as_deref()
311                .unwrap_or(page.url_path.as_str())
312        )
313    );
314
315    // Step 1: load the registry row for this page's type.
316    let pts: Vec<PageType> = match PageType::objects()
317        .where_(PageType::id.eq(page.page_type_id))
318        .fetch(t.pool())
319        .await
320    {
321        Ok(rows) => rows,
322        Err(e) => {
323            tracing::error!(error = %e, "render: failed to fetch PageType row");
324            return (StatusCode::INTERNAL_SERVER_ERROR, "page-type lookup failed").into_response();
325        }
326    };
327    let Some(pt) = pts.into_iter().next() else {
328        return (
329            StatusCode::INTERNAL_SERVER_ERROR,
330            format!(
331                "page_type_id {} has no cms_page_type row",
332                page.page_type_id
333            ),
334        )
335            .into_response();
336    };
337
338    // Step 2: locate the handler. #566 — a type with no code handler
339    // (UI-created, or a code type whose handler drifted out of the
340    // binary) falls back to a `DbSchemaPageType`: it renders via the
341    // row's `default_template` with an empty typed extension. The
342    // authored body still comes from the page-builder value store below,
343    // so a schema-only type renders exactly like a code one — never 500.
344    let handler = find_handler(&pt.type_name)
345        .unwrap_or_else(|| Box::new(crate::page_builder::DbSchemaPageType::from_row(&pt)));
346
347    // Step 3: load the typed extension row as JSON (handler default
348    // returns `Value::Null` when there's no extension table). For
349    // unsaved-content previews the form overlay produces the
350    // extension JSON virtually — nothing hits the persisted row.
351    let page_id = page.id.get().copied().unwrap_or_default();
352    // Extension data for an alias comes from the source row, not
353    // the alias row (the alias has no extension table entry).
354    let extension_id = extension_page_id;
355    let mut extension = if let Some(form) = preview_form {
356        match handler
357            .preview_extension(t.pool(), extension_id, form)
358            .await
359        {
360            Ok(v) => v,
361            Err(e) => {
362                tracing::error!(error = %e, "render: preview_extension failed");
363                return (
364                    StatusCode::INTERNAL_SERVER_ERROR,
365                    "preview extension build failed",
366                )
367                    .into_response();
368            }
369        }
370    } else {
371        match handler.load_extension(t.pool(), extension_id).await {
372            Ok(v) => v,
373            Err(e) => {
374                tracing::error!(error = %e, "render: load_extension failed");
375                return (StatusCode::INTERNAL_SERVER_ERROR, "extension lookup failed")
376                    .into_response();
377            }
378        }
379    };
380
381    // Step 3b: an API view answers here, before Step 4.
382    //
383    // Everything JSON needs — the overlaid `Page`, the virtual extension
384    // built from unsaved form state — is already in hand, and none of
385    // the Step 4 prefetch storm (children, menus, snippets, site
386    // settings, breadcrumbs, stream prerender, themes) applies to a JSON
387    // body. Short-circuiting here makes the JSON path cheaper than the
388    // HTML one, which matters because the editor's preview pane re-runs
389    // it on a one-second debounce.
390    //
391    // Because `render`, `render_with_route` and `render_preview` all
392    // funnel through this function, the admin preview endpoint returns
393    // the real response for free: the editor and the public URL run
394    // literally the same code, so the preview cannot drift from what a
395    // client receives.
396    let view_kind = crate::page_view::resolve_kind(&pt.view_mode, &pt.default_template);
397    let serve_json = force_json
398        || (view_kind.serves_json()
399            && (accept == crate::page_view::Accept::Json || !view_kind.serves_html()));
400    if serve_json {
401        // Resolve the locale here rather than inheriting Step 4's — this
402        // branch returns long before that runs, which is exactly why the
403        // JSON view shipped untranslated: `/fr/…` served canonical text.
404        // Default locale resolves to `None`, since canonical content *is*
405        // the default-locale content and a lookup would be wasted.
406        let json_locale = crate::translation::resolve_locale(t.pool(), locale_code)
407            .await
408            .ok()
409            .flatten();
410        let json_locale_id = json_locale
411            .as_ref()
412            .filter(|l| !l.is_default)
413            .and_then(|l| l.id.get().copied());
414        let builder = crate::page_builder::values::values_for(
415            t.pool(),
416            page_id,
417            page.page_type_id,
418            preview_form,
419        )
420        .await
421        .map(|(values, _)| values);
422        let mut obj = crate::api::pages::detail_object_with_type(
423            t.pool(),
424            page,
425            &pt.type_name,
426            Some(std::mem::take(&mut extension)),
427            builder,
428            json_locale_id,
429            viewer,
430        )
431        .await;
432        crate::api::pages::echo_locale(&mut obj, json_locale.as_ref());
433        let mut resp = axum::Json(serde_json::Value::Object(obj)).into_response();
434        // Tell shared caches the body depends on `Accept`. Stamped only
435        // here, not on every page response: a blanket `Vary: Accept`
436        // would fragment CDN caches site-wide for a feature two page
437        // types use.
438        resp.headers_mut().insert(
439            axum::http::header::VARY,
440            axum::http::HeaderValue::from_static("Accept"),
441        );
442        return resp;
443    }
444
445    // Step 4: assemble Tera context with siblings of the rendered page.
446    //
447    // #249 — children come through the handler hook so index-style
448    // page types can filter (status = published) + order (by
449    // published_at desc) without forcing every template to re-do the
450    // work. The default impl preserves the pre-#249 shape: all
451    // immediate children, sort_order then id.
452    //
453    // #members — the viewer's access oracle, resolved once. Reused to hide
454    // children and menu items the viewer can't access AND installed as a
455    // thread-local so the `can_view` / `visible` Tera helpers guard
456    // hand-written links and lists with the same protection. Bounded,
457    // fixed query count; short-circuits on tenants with nothing gated.
458    //
459    // #748 — the three lookups are independent, so they run together:
460    // one round trip of latency instead of three.
461    let (children, access, ancestors) = rustango::__private_runtime::tokio::join!(
462        handler.children_query(t.pool(), page),
463        crate::view_restriction::access_context(t.pool(), viewer),
464        page.ancestors(t.pool()),
465    );
466    // #723 — a lookup that fails still renders the page, without that
467    // part, but the response is marked `no-store` so the page cache never
468    // keeps the partial page for its whole TTL.
469    let mut degraded = children.is_err() || ancestors.is_err();
470    let children = children.unwrap_or_default();
471    let ancestors = ancestors.unwrap_or_default();
472    // #688 — a gated child's title and URL are as private as its body.
473    // `children_query` decides which pages are live; this decides which
474    // of them this viewer may see listed.
475    let children: Vec<crate::page::Page> = if access.is_unrestricted() {
476        children
477    } else {
478        children
479            .into_iter()
480            .filter(|c| access.can_view(&c.path, c.page_type_id))
481            .collect()
482    };
483
484    // Resolve the request's locale + materialize the
485    // translation overrides for this page AND every page referenced
486    // in the context (children + ancestors). The flat `translations`
487    // map drives the current page; `translations_by_page[id]` is what
488    // templates reach for inside `{% for c in children %}` loops so
489    // card titles / descriptions translate too.
490    let related_ids: Vec<i64> = children
491        .iter()
492        .chain(ancestors.iter())
493        .filter_map(|p| p.id.get().copied())
494        .collect();
495    let (locale, translations, translations_by_page) =
496        match crate::translation::resolve_locale(t.pool(), locale_code).await {
497            Ok(Some(l)) => {
498                if l.is_default {
499                    // Default locale — canonical content IS the
500                    // localized content. Skip the lookup entirely.
501                    (
502                        Some(l),
503                        std::collections::HashMap::new(),
504                        std::collections::HashMap::<
505                            i64,
506                            std::collections::HashMap<String, String>,
507                        >::new(),
508                    )
509                } else {
510                    let lid = l.id.get().copied().unwrap_or_default();
511                    let mut all_ids = related_ids.clone();
512                    all_ids.push(page_id);
513                    // #i18n — grandchildren too, so an index-of-index page
514                    // (teaser cards for posts two levels down) can translate
515                    // them via `translations_by_page`. Ids only, bounded, and
516                    // only off the default locale, where it is needed (#690).
517                    all_ids.extend(grandchild_ids(t.pool(), &children).await);
518                    let by_page = crate::translation::fetch_for_pages(t.pool(), &all_ids, lid)
519                        .await
520                        .unwrap_or_default();
521                    let here = by_page.get(&page_id).cloned().unwrap_or_default();
522                    (Some(l), here, by_page)
523                }
524            }
525            _ => (
526                None,
527                std::collections::HashMap::new(),
528                std::collections::HashMap::new(),
529            ),
530        };
531    // #409 — the active non-default locale id, used to substitute
532    // per-field snippet translations at prefetch. `None` on the default
533    // locale so canonical snippet text renders unchanged.
534    let snippet_locale_id = locale
535        .as_ref()
536        .filter(|l| !l.is_default)
537        .and_then(|l| l.id.get().copied());
538
539    // v0.2 Slice T5 — resolve the active theme for this page (walks
540    // page → ancestors → site default → admin default). The emitted
541    // `<style>` block goes straight into `<head>` via the public
542    // template; tokens are consumed via plain `var(--color-*)`.
543    let (theme_css, theme_slug, theme_default_mode, theme_font_url) =
544        match crate::theme_resolve::resolve_for_page(t.pool(), page).await {
545            Ok(Some(rt)) => {
546                let css = crate::theme::emit_css(&rt.theme, &rt.brand_colors);
547                (
548                    css,
549                    rt.theme.slug.clone(),
550                    rt.theme.default_mode.clone(),
551                    rt.theme.font_url.clone(),
552                )
553            }
554            _ => (
555                String::new(),
556                String::new(),
557                "light".to_owned(),
558                String::new(),
559            ),
560        };
561
562    // Tera's index syntax `m[int_key]` doesn't coerce Number → String
563    // reliably, and JSON object keys must be strings anyway. Convert
564    // the HashMap to string-keyed before inserting into the context
565    // so templates can do `translations_by_page[post.id | as_str]`
566    // — but to keep templates terse we expose a built-in `tr` filter
567    // (registered below) that takes a page id + field and resolves
568    // against `translations_by_page` automatically.
569    let translations_by_page_str: std::collections::HashMap<
570        String,
571        std::collections::HashMap<String, String>,
572    > = translations_by_page
573        .iter()
574        .map(|(k, v)| (k.to_string(), v.clone()))
575        .collect();
576    // #252 — pre-fetch every tag attached to the current page + each
577    // child via a single `IN (…)` query, group by page_id, inject as
578    // a `tags` array on each Page's JSON form. Templates iterate
579    // `{% for tag in page.tags %}` / `{% for tag in post.tags %}`
580    // without further DB hits.
581    let mut tag_ids: Vec<i64> = Vec::with_capacity(children.len() + 1);
582    tag_ids.push(page_id);
583    tag_ids.extend(children.iter().filter_map(|c| c.id.get().copied()));
584    // #842 — each page's categories, the same way.
585    // #863 — and each child's builder values + choice labels, localized,
586    // so a listing's cards read `child.builder.*` in the visitor's language.
587    let child_locale_code = locale.as_ref().filter(|l| !l.is_default).map(|l| l.code.clone());
588    let (tags_by_page, categories_by_page, builder_by_child) = rustango::__private_runtime::tokio::join!(
589        crate::page_tag::prefetch_for_pages(t.pool(), &tag_ids),
590        crate::category::assign::prefetch_for_pages(t.pool(), &tag_ids, snippet_locale_id),
591        crate::page_builder::values::children_builder(
592            t.pool(),
593            &children,
594            &translations_by_page,
595            child_locale_code.as_deref(),
596        ),
597    );
598    let builder_by_child = builder_by_child.unwrap_or_else(|_| {
599        degraded = true;
600        Default::default()
601    });
602    // A child with no share image chosen shows its first photo on cards,
603    // as the page itself does in `og:image`: from its builder fields
604    // (loaded above), else its code-made fields, looked up concurrently.
605    let mut child_photos: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
606    let mut lookups = rustango::__private_runtime::tokio::task::JoinSet::new();
607    for child in children.iter().filter(|c| c.og_image_media_id.is_none()) {
608        let Some(id) = child.id.get().copied() else { continue };
609        match builder_by_child.get(&id) {
610            Some((_, _, Some(photo))) => {
611                child_photos.insert(id, *photo);
612            }
613            Some(_) => {}
614            None => {
615                let (pool, child) = (t.pool().clone(), child.clone());
616                lookups.spawn(async move { (id, crate::meta_tags::fallback_share_image(&pool, &child).await) });
617            }
618        }
619    }
620    while let Some(done) = lookups.join_next().await {
621        if let Ok((id, Some(photo))) = done {
622            child_photos.insert(id, photo);
623        }
624    }
625    let tags_by_page = tags_by_page.unwrap_or_else(|_| {
626        degraded = true;
627        Default::default()
628    });
629    let categories_by_page = categories_by_page.unwrap_or_else(|_| {
630        degraded = true;
631        Default::default()
632    });
633    let attach_tags = |row: &Page| -> serde_json::Value {
634        let mut v = serde_json::to_value(row).unwrap_or(serde_json::Value::Null);
635        if let Some(obj) = v.as_object_mut() {
636            let pid = row.id.get().copied().unwrap_or_default();
637            let list = tags_by_page.get(&pid).cloned().unwrap_or_default();
638            obj.insert(
639                "tags".to_owned(),
640                serde_json::to_value(list).unwrap_or_else(|_| serde_json::Value::Array(vec![])),
641            );
642            let cats = categories_by_page.get(&pid).cloned().unwrap_or_default();
643            obj.insert(
644                "categories".to_owned(),
645                serde_json::to_value(cats).unwrap_or_else(|_| serde_json::Value::Array(vec![])),
646            );
647            if let Some((values, labels, _)) = builder_by_child.get(&pid) {
648                obj.insert("builder".to_owned(), values.clone());
649                obj.insert("builder_labels".to_owned(), labels.clone());
650            }
651            if let Some(photo) = child_photos.get(&pid) {
652                obj.insert("og_image_media_id".to_owned(), serde_json::json!(photo));
653            }
654        }
655        v
656    };
657    let mut page_value = attach_tags(page);
658    let mut children_values: Vec<serde_json::Value> = children.iter().map(attach_tags).collect();
659
660    // #246 — let the handler inject template-visible state
661    // (`latest_posts`, `featured_projects`, etc.) before the
662    // framework's canonical keys are stamped. Stamping
663    // handler-supplied keys FIRST means a typo'd "page" key can't
664    // shadow the canonical `page`; the framework wins every
665    // collision.
666    let mut handler_ctx = handler
667        .public_context(t.pool(), page)
668        .await
669        .unwrap_or_else(|_| {
670            degraded = true;
671            Default::default()
672        });
673
674    // #198 — routable_page: if the resolver routed to this page via
675    // a regex pattern under the canonical `url_path`, merge the
676    // handler's `route_context` on top of `public_context` (same
677    // precedence rule — framework keys win all). The match itself
678    // surfaces as the framework-owned `route_name` + `route_captures`
679    // ctx vars stamped below.
680    let mut route_template: Option<String> = None;
681    if let Some(rm) = route_match {
682        if let Ok(extra) = handler.route_context(t.pool(), page, rm).await {
683            match handler.route_outcome(rm, &extra) {
684                crate::routable::RouteOutcome::Render => {}
685                crate::routable::RouteOutcome::Template(name) => route_template = Some(name),
686                // The caller turns a bare 404 into the site's 404 page.
687                crate::routable::RouteOutcome::NotFound => {
688                    return axum::http::StatusCode::NOT_FOUND.into_response();
689                }
690            }
691            for (k, v) in extra {
692                handler_ctx.insert(k, v);
693            }
694        }
695    }
696
697    // #i18n — engine-level localization. Overlay the seeded per-page
698    // scalar translations onto every page-representing object in the
699    // context (current page, its extension, children, and any handler
700    // card/list objects that carry a page id) so templates render
701    // localized titles/intros/excerpts with no `t`-filter calls —
702    // mirroring the automatic localization StreamField bodies get. No-op
703    // on the default locale (empty `translations_by_page`).
704    let mut ancestors_value = serde_json::to_value(&ancestors).unwrap_or(serde_json::Value::Null);
705    if !translations_by_page.is_empty() {
706        crate::translation::overlay_translations(&mut page_value, &translations_by_page);
707        crate::translation::overlay_translations(&mut extension, &translations_by_page);
708        crate::translation::overlay_translations(&mut ancestors_value, &translations_by_page);
709        for cv in &mut children_values {
710            crate::translation::overlay_translations(cv, &translations_by_page);
711        }
712        for v in handler_ctx.values_mut() {
713            crate::translation::overlay_translations(v, &translations_by_page);
714        }
715    }
716
717    // #936 — a handler extends `page` by returning a `page` object: its
718    // keys are added to the page the template sees; the framework's own
719    // keys (title, url_path, …) win on a clash.
720    if let Some(serde_json::Value::Object(extra)) = handler_ctx.remove("page") {
721        merge_page_extras(&mut page_value, extra);
722    }
723    let mut ctx = Context::new();
724    for (k, v) in handler_ctx {
725        ctx.insert(&k, &v);
726    }
727    ctx.insert("page", &page_value);
728    ctx.insert("page_type", &pt);
729    ctx.insert("extension", &extension);
730    ctx.insert("children", &children_values);
731    ctx.insert("ancestors", &ancestors_value);
732    // #556 — archive context. A page serves as archived either by its
733    // own status or by inheriting from the nearest archived ancestor (an
734    // archived subtree). `ancestors` is already loaded (root→parent
735    // order) so this adds no query — the "zero per-request cost when no
736    // archived roots exist" goal falls out for free. `archived_via` names
737    // that ancestor so hosts can show a "see the latest version" banner.
738    {
739        let archived = crate::page::PageStatus::Archived.as_str();
740        let own_archived = page.status == archived;
741        let archived_ancestor = if own_archived {
742            None
743        } else {
744            ancestors.iter().rev().find(|a| a.status == archived)
745        };
746        ctx.insert(
747            "is_archived",
748            &(own_archived || archived_ancestor.is_some()),
749        );
750        ctx.insert(
751            "archived_via",
752            &archived_ancestor
753                .map(|a| serde_json::json!({ "id": a.id.get().copied(), "title": a.title })),
754        );
755    }
756    // #243 — resolve declared Page↔Snippet M2M relations into
757    // `snippet_relations.<name>` so templates can iterate the chosen
758    // snippets, e.g. `{% for c in snippet_relations.categories %}`.
759    // Resolve failures degrade to an empty list (same as public_context
760    // above) rather than 500-ing the page.
761    {
762        let page_id = page.id.get().copied().unwrap_or_default();
763        let mut snippet_relations = serde_json::Map::new();
764        for (relation, _ty) in handler.snippet_m2m_relations() {
765            let snippets = crate::page_snippet_m2m::related_snippets(t.pool(), page_id, relation)
766                .await
767                .unwrap_or_else(|_| {
768                    degraded = true;
769                    Vec::new()
770                });
771            snippet_relations.insert(
772                relation.to_owned(),
773                serde_json::to_value(&snippets).unwrap_or(serde_json::Value::Null),
774            );
775        }
776        ctx.insert("snippet_relations", &snippet_relations);
777    }
778    // #198 — routable-page surface. `route_name` is the matched
779    // RouteSpec.name; `route_captures` is the `{name → value}` map
780    // of regex named groups. Both keys are framework-owned and
781    // stamp AFTER `public_context` / `route_context` so a typo'd
782    // override can't shadow them.
783    if let Some(rm) = route_match {
784        ctx.insert("route_name", &rm.name);
785        ctx.insert("route_captures", &rm.captures);
786    } else {
787        ctx.insert("route_name", &serde_json::Value::Null);
788        ctx.insert(
789            "route_captures",
790            &std::collections::HashMap::<String, String>::new(),
791        );
792    }
793    ctx.insert("url_prefix", url_prefix);
794    ctx.insert("canonical_url", &canonical_url);
795    ctx.insert("locale", &locale);
796    // #i18n — active locale code as `LANG` so public templates can
797    // localize hardcoded chrome (UI labels not stored as page content)
798    // via the framework `translate(locale=LANG)` fn/filter, mirroring the
799    // admin. Falls back to "en" when no locale resolved.
800    let lang_code = locale.as_ref().map_or("en", |l| l.code.as_str());
801    ctx.insert("LANG", lang_code);
802    // #i18n — writing direction for the active locale so public templates
803    // can set `<html dir>`. Core knows the RTL scripts (ar/he/fa/…), so an
804    // RTL locale added purely via `cms_locale` renders RTL without extra
805    // config. Mirrors the admin's `LANG_DIR`.
806    ctx.insert("DIR", rustango::i18n::text_direction(lang_code));
807    ctx.insert("translations", &translations);
808    ctx.insert("translations_by_page", &translations_by_page_str);
809    ctx.insert("theme_css", &theme_css);
810    ctx.insert("theme_slug", &theme_slug);
811    ctx.insert("theme_default_mode", &theme_default_mode);
812    ctx.insert("theme_font_url", &theme_font_url);
813
814    // Prefetch every Library snippet under the tenant's schema so
815    // `{{ cms_snippet(slug=…) }}` resolves without the DB: the maps go
816    // into the context as `_snippets_html*` and, for the function, into a
817    // thread-local installed with the others below (#845).
818    let (snippets_html, snippets_html_inline) =
819        crate::snippet::prefetch_all(t.pool(), snippet_locale_id)
820            .await
821            .unwrap_or_else(|_| {
822                degraded = true;
823                Default::default()
824            });
825    ctx.insert("_snippets_html", &snippets_html);
826    ctx.insert("_snippets_html_inline", &snippets_html_inline);
827
828    // Pre-render every `WidgetKind::Stream` extension field to HTML
829    // before Tera fires. The `stream_render(name="…")` Tera function
830    // reads from `_stream_html` — mirrors the `cms_snippet` shape so
831    // the public template just does `{{ stream_render(name="body_stream") | safe }}`.
832    // The widget list says where the body is. Without it there is no body
833    // to render, so this fails like `load_extension` (#723).
834    let stream_widgets = match handler.widgets(t.pool(), page_id).await {
835        Ok(w) => w,
836        Err(e) => {
837            tracing::error!(error = %e, "render: widgets lookup failed");
838            return (StatusCode::INTERNAL_SERVER_ERROR, "page fields lookup failed").into_response();
839        }
840    };
841    // Use the async variant so chooser blocks (page_chooser /
842    // snippet_chooser / document_chooser / image) get enriched with
843    // resolved row data (`_url`, `_title`, etc.) before the sync
844    // template walker fires.
845    let mut stream_html = match crate::block::tera_helpers::prerender_extension_streams_async_with(
846        &stream_widgets,
847        &extension,
848        tera,
849        t.pool(),
850        &translations,
851        snippet_locale_id, // #550 FB-17 — localize embedded form blocks
852        // Host enrichers get the page, so a block can inherit from it,
853        // and the tenant, so anything they cache stays per-tenant.
854        page.id.get().copied(),
855        &t.org.slug,
856    )
857    .await
858    {
859        Ok(map) => map,
860        Err(e) => {
861            tracing::warn!(
862                target: "rustango_cms::block",
863                error = %e,
864                "stream pre-render failed; falling back to empty",
865            );
866            degraded = true;
867            std::collections::HashMap::new()
868        }
869    };
870
871    // #565 — page-builder body. When the page type has a published
872    // schema, expose the filled values as `builder.*` (scalars + nested
873    // groups) and merge each flexible-content/repeater zone's rendered
874    // HTML into `_stream_html` so `{{ stream_render(name="<zone>") }}`
875    // resolves. Under preview, values come from the posted form so the
876    // iframe reflects unsaved edits. Additive to code handler streams.
877    let mut builder_media: Option<i64> = None;
878    if let Some(built) = crate::page_builder::values::public_render(
879        t.pool(),
880        extension_id,
881        page.page_type_id,
882        preview_form,
883        &translations,
884        tera,
885        snippet_locale_id,
886        page.id.get().copied(),
887        &t.org.slug,
888        locale.as_ref().filter(|l| !l.is_default).map(|l| l.code.as_str()),
889    )
890    .await
891    {
892        ctx.insert("builder", &built.values);
893        // #863 — choice fields' labels in the visitor's language.
894        ctx.insert("builder_labels", &built.labels);
895        // Generic pre-rendered body for the fallback template (UI types).
896        ctx.insert("builder_html", &built.body_html);
897        stream_html.extend(built.zone_html);
898        builder_media = built.first_media_id;
899    }
900    ctx.insert("_stream_html", &stream_html);
901
902    // Share image: when the editor chose none on the Promote tab, the
903    // page's first photo stands in — what the Promote tab has always
904    // promised, and what `rcms_meta_tags` then emits as `og:image`.
905    if page_value.get("og_image_media_id").map_or(true, serde_json::Value::is_null) {
906        let fallback = crate::meta_tags::first_image_in_extension(&stream_widgets, &extension).or(builder_media);
907        if let (Some(id), Some(obj)) = (fallback, page_value.as_object_mut()) {
908            obj.insert("og_image_media_id".to_owned(), serde_json::json!(id));
909            ctx.insert("page", &page_value);
910        }
911    }
912    ctx.insert("site_origin", &site_origin);
913
914    // #247 — resolve any `*_id` field on the extension that points
915    // at a `cms_page` row, exposing both a `_pages_by_id` ctx map AND
916    // the `pageurl(id=…)` Tera function. The function reads from a thread-local that's set
917    // here and cleared the moment the render returns, dodging Tera's
918    // "functions can't see context" limitation without paying the
919    // per-render `Tera::clone()` tax.
920    let pages_by_id = crate::page_url::prefetch_for_extension(&extension, t.pool()).await;
921    // The string-keyed shape is what `_pages_by_id[id | string]` style
922    // template access wants (JSON object keys must be strings; Tera's
923    // map index doesn't coerce Number → String reliably).
924    let pages_by_id_str: std::collections::HashMap<String, String> = pages_by_id
925        .iter()
926        .map(|(k, v)| (k.to_string(), v.clone()))
927        .collect();
928    ctx.insert("_pages_by_id", &pages_by_id_str);
929    // #244 — pre-fetch every `show_in_menus = true AND
930    // status = "published"` page once per render so the
931    // `auto_menu(parent_id=…, depth=…)` Tera function can build the
932    // nested item tree from the in-memory pool. The pool is bounded
933    // by menu-eligible cardinality (typically tens), so this is
934    // cheaper than letting each `auto_menu` call re-query.
935    // #316 — when the public router runs a page cache, reuse the same
936    // backend to cache the menu-eligible tree query (shared across
937    // every URL of the tenant). Keyed by tenant slug; TTL mirrors the
938    // page cache so menu staleness matches page staleness. Preview /
939    // admin renders pass `None` and always query live.
940    //
941    // #250 / #245 — the snippet and site-setting prefetches (documented
942    // below) don't depend on the menu, so all three run together (#748).
943    let menu_fut = async {
944        match cache {
945            Some((c, ttl)) => {
946                let key = format!("rcms:menu:{}", t.org.slug);
947                crate::auto_menu::prefetch_cached(t.pool(), c, &key, Some(ttl)).await
948            }
949            None => crate::auto_menu::prefetch(t.pool()).await,
950        }
951    };
952    // #639 — the curated menus `menu(slug=…)` reads, filtered for this
953    // viewer, localized and marked against this page. One query when the
954    // tenant has no menus.
955    let curated_fut = crate::navigation::resolve_menus_with(
956        t.pool(),
957        None,
958        crate::navigation::MenuOptions {
959            viewer,
960            locale: locale.as_ref(),
961            current: Some(page),
962        },
963    );
964    let (menu_rows, site_settings, curated_menus) = rustango::__private_runtime::tokio::join!(
965        menu_fut,
966        crate::site_setting::prefetch_for_render(t.pool(), child_locale_code.as_deref()),
967        curated_fut,
968    );
969    degraded |= curated_menus.is_err();
970    let curated_menus = curated_menus.unwrap_or_default();
971    // #i18n — localize menu titles for the active locale so `auto_menu()`
972    // nav (sidebars, footers, switchers) shows translated labels, not just
973    // the canonical ones. The prefetched rows are canonical (cached
974    // per-tenant, locale-agnostic), so translate a per-request copy here —
975    // before the await-free install block — using the same per-field
976    // `cms_translation` overrides the `t` filter reads. Menu pages live
977    // anywhere in the tree (not just the current page's children/
978    // ancestors), so this is a separate, bounded lookup over the
979    // menu-eligible ids. Default locale / no menu rows → no-op.
980    let menu_rows = match &locale {
981        Some(l) if !l.is_default && !menu_rows.is_empty() => {
982            let lid = l.id.get().copied().unwrap_or_default();
983            let menu_ids: Vec<i64> = menu_rows.iter().map(|r| r.id).collect();
984            let menu_tr = crate::translation::fetch_for_pages(t.pool(), &menu_ids, lid)
985                .await
986                .unwrap_or_default();
987            menu_rows
988                .into_iter()
989                .map(|mut r| {
990                    if let Some(title) = menu_tr
991                        .get(&r.id)
992                        .and_then(|m| m.get("title"))
993                        .filter(|s| !s.is_empty())
994                    {
995                        r.title = title.clone();
996                    }
997                    r
998                })
999                .collect()
1000        }
1001        _ => menu_rows,
1002    };
1003
1004    let menu_rows = filter_menu_rows_for_viewer(&access, menu_rows);
1005    // #640 — the rows are cached tenant-wide with tenant-absolute paths;
1006    // this request's copy gets the site's public paths.
1007    let mut menu_rows = menu_rows;
1008    let mut curated_menus = curated_menus;
1009    if !site_prefix.is_empty() {
1010        for row in &mut menu_rows {
1011            row.url_path = crate::site::to_public_path(site_prefix, &row.url_path);
1012        }
1013        for menu in curated_menus.values_mut() {
1014            crate::navigation::rebase_page_urls(&mut menu.items, site_prefix);
1015        }
1016    }
1017
1018    // #250 / #731 — `snippet_html(type=…, id=N)` records what the page
1019    // asks for during `tera.render`; `snippet_render::fill` renders just
1020    // those rows afterwards (one per key, however often it is referenced).
1021    //
1022    // #245 — `site_settings` holds every `cms_site_setting` row for the
1023    // `site_setting(scope=…)` Tera function. Bounded by distinct-scope
1024    // count (tens typically); one query covers every reference in the
1025    // rendered template.
1026    // Auto-inject the analytics beacon on real page renders (not editor
1027    // previews) unless disabled via the `analytics` site setting. Computed
1028    // here before `site_settings` is moved into `install()` below.
1029    let inject_beacon = preview_form.is_none() && crate::analytics::enabled(&site_settings);
1030
1031    // Install every render-scoped thread-local in ONE await-free block
1032    // immediately before the synchronous `tera.render`. Each helper
1033    // (`pageurl`, `children_filtered`, `auto_menu`, `snippet_html`,
1034    // `site_setting`) stashes its data in a thread-local. If an
1035    // `.await` ran between an install and the render, tokio's
1036    // work-stealing scheduler could resume the render on a different
1037    // worker thread where the thread-local was never set (or still
1038    // held a prior request's data the guard cleared elsewhere) —
1039    // surfacing as an intermittently-empty `auto_menu` nav. Doing all
1040    // prefetch awaits above and every install here, with no await
1041    // before render, pins all five thread-locals to the rendering
1042    // thread.
1043    let _pageurl_guard = crate::page_url::install(pages_by_id); // #247
1044    let _url_prefix_guard = crate::page_url::install_url_prefix(url_prefix); // page_href
1045    // Installed HERE, with the other guards and after every await, for the
1046    // reason the block above documents: a thread hop mid-render drops a
1047    // thread-local installed earlier, which showed up once as an
1048    // intermittently-empty nav.
1049    let _site_prefix_guard = crate::page_url::install_site_prefix(site_prefix);
1050    let _children_guard = crate::children_filtered::install(page_id, children.clone()); // #249
1051    let _auto_menu_guard = crate::auto_menu::install(menu_rows); // #244/#316
1052    let _menus_guard = crate::navigation::install(curated_menus); // #639 — menu(slug=…)
1053    let _cms_snippets_guard = crate::snippet::install(snippets_html, snippets_html_inline); // #845 — cms_snippet(slug=…)
1054    let _access_guard = crate::access::install(access); // #members — can_view / visible
1055    let snippet_recorder = crate::snippet_render::record(); // #250 / #731
1056                                                                                // #565 — `stream_render(name="…")` reads this thread-local (Tera 1.20
1057                                                                                // functions can't see context); feeds code stream fields + builder zones.
1058    let _stream_html_guard = crate::block::tera_helpers::install(stream_html);
1059    let _site_settings_guard = crate::site_setting::install(site_settings); // #245
1060                                                                            // #401 — install the stashed language-switcher entries on *this*
1061                                                                            // thread so `language_switcher()` resolves during `tera.render`.
1062    let _switcher_guard = pending_switcher.map(crate::language_switcher::install);
1063
1064    // Step 5: render. Tera errors come back with the template name +
1065    // line, so we surface them verbatim — debugging is much easier
1066    // than a generic "template error" message.
1067    //
1068    // A page may name its own template instead of its type's. An
1069    // override that doesn't resolve falls back rather than failing:
1070    // the name is editor-typed and may point at a template that was
1071    // renamed or never created, and a page going dark over a typo is a
1072    // worse outcome than one rendering in its type's default layout.
1073    let template = choose_template(
1074        route_template.as_deref(),
1075        &page.template_override,
1076        &pt.default_template,
1077        tera,
1078        page.id.get().copied().unwrap_or_default(),
1079    );
1080    let rendered = tera.render(template, &ctx);
1081    let snippet_keys = snippet_recorder.take();
1082    // Every thread-local guard above is only needed for `tera.render`.
1083    // Clear them before awaiting: snippet templates rendered by `fill`
1084    // must see the same (empty) helpers whichever thread resumes it.
1085    drop((
1086        _pageurl_guard,
1087        _url_prefix_guard,
1088        _site_prefix_guard,
1089        _children_guard,
1090        _auto_menu_guard,
1091        _menus_guard,
1092        _cms_snippets_guard,
1093        _access_guard,
1094        _stream_html_guard,
1095        _site_settings_guard,
1096        _switcher_guard,
1097    ));
1098    match rendered {
1099        Ok(html) => {
1100            let html = crate::snippet_render::fill(t.pool(), tera, snippet_locale_id, html, snippet_keys).await;
1101            // Rich-text internal links anywhere in the page — extension
1102            // fields and stream blocks alike (#682).
1103            let html = crate::richtext::resolve_internal_links(t.pool(), html).await;
1104            let html = if inject_beacon {
1105                crate::analytics::inject_beacon(html)
1106            } else {
1107                html
1108            };
1109            if crate::admin_bar::active() || crate::template_inspector::active() {
1110                // A signed-in admin's own view (admin bar, template
1111                // inspector): never cached.
1112                let mut html = html;
1113                if crate::template_inspector::active() {
1114                    html = crate::template_inspector::annotate(html, tera, template, &t.org.slug);
1115                }
1116                let html = crate::admin_bar::add(html, page.id.get().copied().unwrap_or_default());
1117                return page_response(html, true);
1118            }
1119            page_response(html, degraded)
1120        }
1121        Err(e) => {
1122            let mut chain = e.to_string();
1123            let mut src: Option<&dyn std::error::Error> = std::error::Error::source(&e);
1124            while let Some(s) = src {
1125                chain.push_str("\n  caused by: ");
1126                chain.push_str(&s.to_string());
1127                src = s.source();
1128            }
1129            tracing::error!(template = %pt.default_template, error = %chain, "render: tera failed");
1130            (
1131                StatusCode::INTERNAL_SERVER_ERROR,
1132                format!("template `{}` failed:\n{}", pt.default_template, chain),
1133            )
1134                .into_response()
1135        }
1136    }
1137}
1138
1139/// A rendered page as a response. A `degraded` page — one rendered with a
1140/// failed lookup left empty — is marked `no-store`, which the page cache
1141/// and any shared cache skip, so the gap lasts one request rather than a
1142/// whole TTL.
1143fn page_response(html: String, degraded: bool) -> Response {
1144    let mut resp = Html(html).into_response();
1145    if degraded {
1146        resp.headers_mut().insert(
1147            axum::http::header::CACHE_CONTROL,
1148            axum::http::HeaderValue::from_static("no-store"),
1149        );
1150    }
1151    resp
1152}
1153
1154/// Which template a page renders through: its own override when it
1155/// names one that exists, otherwise its page type's.
1156///
1157/// The existence check is what makes the override safe to expose to
1158/// editors and agents. An override is a free-typed name — it can point
1159/// at a template that was renamed, deleted, or never created — and a
1160/// page going dark over a typo is a worse failure than one rendering in
1161/// its type's layout. The mismatch is logged rather than swallowed, so
1162/// the reason is findable.
1163/// Add a handler's `page` keys to the page object; existing keys win.
1164fn merge_page_extras(page: &mut serde_json::Value, extra: serde_json::Map<String, serde_json::Value>) {
1165    if let serde_json::Value::Object(map) = page {
1166        for (k, v) in extra {
1167            map.entry(k).or_insert(v);
1168        }
1169    }
1170}
1171
1172/// The template to render: a routable pattern's own template when Tera
1173/// knows it, else the page's override, else its type's template.
1174fn choose_template<'a>(
1175    route_template: Option<&'a str>,
1176    override_name: &'a str,
1177    default_template: &'a str,
1178    tera: &Tera,
1179    page_id: i64,
1180) -> &'a str {
1181    match route_template {
1182        Some(name) if tera.get_template_names().any(|n| n == name) => name,
1183        _ => pick_template(override_name, default_template, tera, page_id),
1184    }
1185}
1186
1187fn pick_template<'a>(
1188    override_name: &'a str,
1189    default_template: &'a str,
1190    tera: &Tera,
1191    page_id: i64,
1192) -> &'a str {
1193    let over = override_name.trim();
1194    if over.is_empty() {
1195        return default_template;
1196    }
1197    if tera.get_template_names().any(|n| n == over) {
1198        return over;
1199    }
1200    tracing::warn!(
1201        target: "rustango_cms::render",
1202        page_id,
1203        template = %over,
1204        "page template_override does not resolve; using the page type's template",
1205    );
1206    default_template
1207}
1208
1209// ===================================================================
1210// #members — viewer-aware menu filtering.
1211// ===================================================================
1212
1213/// Drop menu rows the viewer may not access, using the pre-built
1214/// [`AccessContext`](crate::view_restriction::AccessContext) — in-memory,
1215/// no queries.
1216fn filter_menu_rows_for_viewer(
1217    access: &crate::view_restriction::AccessContext,
1218    rows: Vec<crate::auto_menu::MenuRow>,
1219) -> Vec<crate::auto_menu::MenuRow> {
1220    if rows.is_empty() || access.is_unrestricted() {
1221        return rows;
1222    }
1223    rows.into_iter()
1224        .filter(|r| access.can_view(&r.path, r.page_type_id))
1225        .collect()
1226}
1227
1228#[cfg(test)]
1229mod tests {
1230    use super::pick_template;
1231
1232    fn tera_with(names: &[&str]) -> tera::Tera {
1233        let mut t = tera::Tera::default();
1234        for n in names {
1235            t.add_raw_template(n, "x").expect("template");
1236        }
1237        t
1238    }
1239
1240    #[test]
1241    fn no_override_uses_the_page_types_template() {
1242        let t = tera_with(&["type.html"]);
1243        assert_eq!(pick_template("", "type.html", &t, 1), "type.html");
1244    }
1245
1246    #[test]
1247    fn whitespace_only_override_counts_as_none() {
1248        let t = tera_with(&["type.html"]);
1249        assert_eq!(pick_template("   ", "type.html", &t, 1), "type.html");
1250    }
1251
1252    #[test]
1253    fn an_existing_override_wins() {
1254        let t = tera_with(&["type.html", "fy2027/report.html"]);
1255        assert_eq!(
1256            pick_template("fy2027/report.html", "type.html", &t, 1),
1257            "fy2027/report.html"
1258        );
1259    }
1260
1261    #[test]
1262    fn override_is_trimmed_before_lookup() {
1263        let t = tera_with(&["type.html", "fy2027/report.html"]);
1264        assert_eq!(
1265            pick_template("  fy2027/report.html\n", "type.html", &t, 1),
1266            "fy2027/report.html"
1267        );
1268    }
1269
1270    #[test]
1271    fn a_missing_override_falls_back_instead_of_breaking_the_page() {
1272        // The whole point of the existence check: a renamed or
1273        // mistyped template must not take the page down.
1274        let t = tera_with(&["type.html"]);
1275        assert_eq!(pick_template("gone.html", "type.html", &t, 1), "type.html");
1276    }
1277}
1278
1279#[cfg(test)]
1280mod page_response_tests {
1281    use super::page_response;
1282
1283    #[test]
1284    fn a_degraded_page_is_never_stored() {
1285        let whole = page_response("<p>ok</p>".to_owned(), false);
1286        assert!(whole.headers().get(axum::http::header::CACHE_CONTROL).is_none());
1287        let partial = page_response("<p>partial</p>".to_owned(), true);
1288        assert_eq!(
1289            partial.headers().get(axum::http::header::CACHE_CONTROL).map(|v| v.to_str().unwrap_or("")),
1290            Some("no-store")
1291        );
1292    }
1293}
1294
1295#[cfg(test)]
1296mod choose_template_tests {
1297    use super::*;
1298
1299    #[test]
1300    fn handler_page_keys_extend_the_page_without_overriding_it() {
1301        let mut page = serde_json::json!({"title": "Real", "url_path": "/a"});
1302        let extra = serde_json::json!({"title": "Fake", "goal_amount": 500});
1303        let serde_json::Value::Object(extra) = extra else { unreachable!() };
1304        merge_page_extras(&mut page, extra);
1305        assert_eq!(page["title"], "Real", "framework keys win");
1306        assert_eq!(page["goal_amount"], 500, "handler keys are added");
1307    }
1308
1309    #[test]
1310    fn a_route_template_wins_when_it_exists() {
1311        let mut tera = Tera::default();
1312        tera.add_raw_templates(vec![("type.html", ""), ("route.html", ""), ("override.html", "")])
1313            .unwrap();
1314        assert_eq!(choose_template(Some("route.html"), "override.html", "type.html", &tera, 1), "route.html");
1315        assert_eq!(choose_template(Some("missing.html"), "override.html", "type.html", &tera, 1), "override.html");
1316        assert_eq!(choose_template(None, "", "type.html", &tera, 1), "type.html");
1317    }
1318}