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