Skip to main content

rustango_cms/
children_filtered.rs

1//! `children_filtered(...)` Tera helper — a page's live children,
2//! filtered and ordered.
3//!
4//! Pairs with [`crate::page_type::PageTypeHandler::children_query`]:
5//! the handler hook decides what's in `children` (the typed list the
6//! template iterates by default); this template-side function lets a
7//! template re-filter, reorder, or truncate that same list at the
8//! call site — useful when one template wants two slices of the same
9//! tree (e.g. "recent" + "highlighted").
10//!
11//! Operates purely on the in-memory list installed by the render
12//! pipeline; no DB round-trip from the function (same constraint as
13//! [`crate::page_url`] — Tera 1.x function args don't see context, so
14//! we route the data through a thread-local that's set + cleared
15//! around `tera.render`).
16//!
17//! ## Usage in templates
18//!
19//! ```text
20//! {% set posts = children_filtered(status="published", order_by="-published_at", limit=20) %}
21//! {% for p in posts %}
22//!   <a href="{{ p.url_path }}">{{ p.title }}</a>
23//! {% endfor %}
24//! ```
25//!
26//! ## Arguments
27//!
28//! - `status` — keep only rows where `Page.status` matches the given
29//!   string. Omit to skip the filter.
30//! - `order_by` — sort key. `"field"` ascending, `"-field"`
31//!   descending. Recognized: `sort_order`, `id`, `title`, `slug`,
32//!   `depth`, `published_at`, `created_at`, `updated_at`. Unknown
33//!   field → unsorted (with a debug-level warning). Omit to keep
34//!   the handler's order.
35//! - `limit` — truncate to first N rows after sort. `0` or omitted →
36//!   no limit.
37//! - `parent_id` — optional sanity check; when supplied, the function
38//!   verifies it matches the rendered page's id and returns an empty
39//!   list otherwise. The list is always the rendered page's children
40//!   — handlers that need a different parent should expose a custom
41//!   ctx var instead.
42
43use std::cell::RefCell;
44use std::cmp::Ordering;
45use std::sync::Arc;
46
47use tera::{Function, Tera, Value};
48
49use crate::page::Page;
50
51thread_local! {
52    /// Per-thread `(rendered_page_id, children_list)` pair. Installed
53    /// for the duration of one `tera.render` call. Holds owned
54    /// `Page` rows so the function can re-serialize them without
55    /// keeping a reference to render-local state.
56    static CURRENT_CHILDREN: RefCell<Option<Arc<ChildrenSnapshot>>>
57        = const { RefCell::new(None) };
58}
59
60struct ChildrenSnapshot {
61    /// The id of the page being rendered. `parent_id=` kwarg validates
62    /// against this so a template can't silently filter the wrong
63    /// list.
64    rendered_page_id: i64,
65    children: Vec<Page>,
66}
67
68/// RAII guard. While in scope the rendered page's children are
69/// readable via `children_filtered(...)`; on drop the thread-local
70/// is cleared so a follow-up render on the same tokio worker
71/// doesn't inherit stale data.
72#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
73pub struct ChildrenGuard {
74    _priv: (),
75}
76
77impl Drop for ChildrenGuard {
78    fn drop(&mut self) {
79        CURRENT_CHILDREN.with(|cell| {
80            *cell.borrow_mut() = None;
81        });
82    }
83}
84
85/// Install the rendered page's children for the duration of the
86/// returned guard. `rendered_page_id` is the id `parent_id=` should
87/// match — pass the page row's own id.
88pub fn install(rendered_page_id: i64, children: Vec<Page>) -> ChildrenGuard {
89    CURRENT_CHILDREN.with(|cell| {
90        *cell.borrow_mut() = Some(Arc::new(ChildrenSnapshot {
91            rendered_page_id,
92            children,
93        }));
94    });
95    ChildrenGuard { _priv: () }
96}
97
98/// Register the `children_filtered` Tera function. Called once at
99/// Tera setup — wired from [`crate::urls::register_tera_helpers`].
100pub fn register_tera_function(tera: &mut Tera) {
101    tera.register_function("children_filtered", ChildrenFilteredFn);
102}
103
104struct ChildrenFilteredFn;
105
106impl Function for ChildrenFilteredFn {
107    fn call(&self, args: &std::collections::HashMap<String, Value>) -> tera::Result<Value> {
108        let snap = CURRENT_CHILDREN.with(|cell| cell.borrow().clone());
109        let Some(snap) = snap else {
110            // No render in flight (or the helper is being called from
111            // a non-rendered Tera invocation, e.g. macro expansion in
112            // an admin form). Return an empty list rather than erroring
113            // so the template gracefully renders nothing.
114            return Ok(Value::Array(Vec::new()));
115        };
116
117        // parent_id sanity check (optional). Mismatch returns empty so
118        // templates fail-soft instead of silently filtering the wrong
119        // page's children.
120        if let Some(pid) = args.get("parent_id").and_then(Value::as_i64) {
121            if pid != snap.rendered_page_id {
122                return Ok(Value::Array(Vec::new()));
123            }
124        }
125
126        let mut out: Vec<Page> = snap.children.clone();
127
128        // status filter
129        if let Some(want) = args.get("status").and_then(Value::as_str) {
130            out.retain(|p| p.status == want);
131        }
132
133        // order_by — '-field' desc, 'field' asc. Unknown field leaves
134        // the order untouched but emits a debug log so a typo doesn't
135        // silently ignore the kwarg.
136        if let Some(spec) = args.get("order_by").and_then(Value::as_str) {
137            let (desc, field) = match spec.strip_prefix('-') {
138                Some(f) => (true, f),
139                None => (false, spec),
140            };
141            if !sort_by_field(&mut out, field, desc) {
142                tracing::debug!(
143                    target: "rustango_cms::children_filtered",
144                    field,
145                    "children_filtered: unrecognized order_by field; leaving order unchanged",
146                );
147            }
148        }
149
150        // limit (0 = unlimited; treat negative as unlimited too)
151        if let Some(n) = args.get("limit").and_then(Value::as_i64) {
152            if n > 0 {
153                out.truncate(n as usize);
154            }
155        }
156
157        serde_json::to_value(&out).map_err(|e| {
158            tera::Error::msg(format!(
159                "children_filtered: serializing filtered pages failed: {e}"
160            ))
161        })
162    }
163}
164
165/// Return `true` if `field` matched a known sort key; `false`
166/// means the caller's input didn't match anything and the order
167/// was left as-is. Compares via a stable secondary key (`id`) so
168/// ties don't reshuffle between renders.
169fn sort_by_field(rows: &mut [Page], field: &str, desc: bool) -> bool {
170    let cmp: fn(&Page, &Page) -> Ordering = match field {
171        "sort_order" => |a, b| a.sort_order.cmp(&b.sort_order).then(cmp_id(a, b)),
172        "id" => cmp_id,
173        "title" => |a, b| a.title.cmp(&b.title).then(cmp_id(a, b)),
174        "slug" => |a, b| a.slug.cmp(&b.slug).then(cmp_id(a, b)),
175        "depth" => |a, b| a.depth.cmp(&b.depth).then(cmp_id(a, b)),
176        "published_at" => |a, b| a.published_at.cmp(&b.published_at).then(cmp_id(a, b)),
177        "last_published_at" => |a, b| {
178            a.last_published_at
179                .cmp(&b.last_published_at)
180                .then(cmp_id(a, b))
181        },
182        "created_at" => |a, b| {
183            a.created_at
184                .get()
185                .copied()
186                .cmp(&b.created_at.get().copied())
187                .then(cmp_id(a, b))
188        },
189        "updated_at" => |a, b| {
190            a.updated_at
191                .get()
192                .copied()
193                .cmp(&b.updated_at.get().copied())
194                .then(cmp_id(a, b))
195        },
196        _ => return false,
197    };
198    if desc {
199        rows.sort_by(|a, b| cmp(b, a));
200    } else {
201        rows.sort_by(cmp);
202    }
203    true
204}
205
206fn cmp_id(a: &Page, b: &Page) -> Ordering {
207    a.id.get().copied().cmp(&b.id.get().copied())
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use chrono::{TimeZone, Utc};
214    use rustango::sql::Auto;
215    use serde_json::json;
216    use tera::{Context, Tera};
217
218    fn page(id: i64, slug: &str, status: &str, published_at: Option<i64>) -> Page {
219        Page {
220            id: Auto::Set(id),
221            page_type_id: 1,
222            title: format!("Title {id}"),
223            slug: slug.to_owned(),
224            path: format!("{id:04}/"),
225            url_path: format!("/{slug}"),
226            preview_path: String::new(),
227            template_override: String::new(),
228            depth: 1,
229            parent_id: Some(99),
230            locale_variant_of: None,
231            alias_of: None,
232            theme_id: None,
233            sort_order: id as i32,
234            status: status.to_owned(),
235            published_at: published_at.map(|t| Utc.timestamp_opt(t, 0).single().unwrap()),
236            last_published_at: published_at.map(|t| Utc.timestamp_opt(t, 0).single().unwrap()),
237            go_live_at: None,
238            expire_at: None,
239            seo_title: String::new(),
240            seo_description: String::new(),
241            robots_index: true,
242            sitemap_priority: 0.5,
243            show_in_menus: false,
244            og_title: String::new(),
245            og_description: String::new(),
246            og_image_media_id: None,
247            twitter_card: String::from("summary_large_image"),
248            notification_pre_published_sent: false,
249            created_at: Auto::Set(Utc.timestamp_opt(0, 0).single().unwrap()),
250            updated_at: Auto::Set(Utc.timestamp_opt(0, 0).single().unwrap()),
251        }
252    }
253
254    fn fresh_tera() -> Tera {
255        let mut tera = Tera::default();
256        register_tera_function(&mut tera);
257        tera
258    }
259
260    fn render(tera: &Tera, src: &str) -> String {
261        let mut t = tera.clone();
262        t.add_raw_template("t.html", src).unwrap();
263        t.render("t.html", &Context::new()).unwrap()
264    }
265
266    #[test]
267    fn returns_empty_when_nothing_installed() {
268        let tera = fresh_tera();
269        let out = render(&tera, r#"{{ children_filtered() | length }}"#);
270        assert_eq!(out, "0");
271    }
272
273    #[test]
274    fn returns_full_list_when_no_filters_applied() {
275        let _g = install(
276            99,
277            vec![page(1, "a", "published", None), page(2, "b", "draft", None)],
278        );
279        let tera = fresh_tera();
280        let out = render(&tera, r#"{{ children_filtered() | length }}"#);
281        assert_eq!(out, "2");
282    }
283
284    #[test]
285    fn filters_by_status() {
286        let _g = install(
287            99,
288            vec![
289                page(1, "a", "published", None),
290                page(2, "b", "draft", None),
291                page(3, "c", "published", None),
292            ],
293        );
294        let tera = fresh_tera();
295        let out = render(
296            &tera,
297            r#"{% set p = children_filtered(status="published") %}{{ p | length }}|{{ p[0].slug }}"#,
298        );
299        assert_eq!(out, "2|a");
300    }
301
302    #[test]
303    fn orders_by_published_at_desc() {
304        let _g = install(
305            99,
306            vec![
307                page(1, "a", "published", Some(100)),
308                page(2, "b", "published", Some(300)),
309                page(3, "c", "published", Some(200)),
310            ],
311        );
312        let tera = fresh_tera();
313        let out = render(
314            &tera,
315            r#"{% for p in children_filtered(order_by="-published_at") %}{{ p.slug }} {% endfor %}"#,
316        );
317        assert_eq!(out, "b c a ");
318    }
319
320    #[test]
321    fn orders_by_title_asc() {
322        let _g = install(
323            99,
324            vec![
325                page(3, "c", "published", None),
326                page(1, "a", "published", None),
327                page(2, "b", "published", None),
328            ],
329        );
330        let tera = fresh_tera();
331        let out = render(
332            &tera,
333            r#"{% for p in children_filtered(order_by="title") %}{{ p.slug }} {% endfor %}"#,
334        );
335        // titles "Title 1" < "Title 2" < "Title 3" ascending
336        assert_eq!(out, "a b c ");
337    }
338
339    #[test]
340    fn limit_truncates_after_sort() {
341        let _g = install(
342            99,
343            vec![
344                page(1, "a", "published", Some(100)),
345                page(2, "b", "published", Some(300)),
346                page(3, "c", "published", Some(200)),
347            ],
348        );
349        let tera = fresh_tera();
350        let out = render(
351            &tera,
352            r#"{% for p in children_filtered(order_by="-published_at", limit=2) %}{{ p.slug }} {% endfor %}"#,
353        );
354        assert_eq!(out, "b c ");
355    }
356
357    #[test]
358    fn parent_id_mismatch_returns_empty() {
359        let _g = install(99, vec![page(1, "a", "published", None)]);
360        let tera = fresh_tera();
361        let out = render(&tera, r#"{{ children_filtered(parent_id=42) | length }}"#);
362        assert_eq!(out, "0");
363    }
364
365    #[test]
366    fn parent_id_match_passes() {
367        let _g = install(99, vec![page(1, "a", "published", None)]);
368        let tera = fresh_tera();
369        let out = render(&tera, r#"{{ children_filtered(parent_id=99) | length }}"#);
370        assert_eq!(out, "1");
371    }
372
373    #[test]
374    fn unknown_order_by_leaves_input_order() {
375        let _g = install(
376            99,
377            vec![
378                page(3, "c", "published", None),
379                page(1, "a", "published", None),
380            ],
381        );
382        let tera = fresh_tera();
383        let out = render(
384            &tera,
385            r#"{% for p in children_filtered(order_by="bogus_field") %}{{ p.slug }} {% endfor %}"#,
386        );
387        // Input order preserved (c, a) — unknown field doesn't sort.
388        assert_eq!(out, "c a ");
389    }
390
391    #[test]
392    fn guard_clears_thread_local() {
393        {
394            let _g = install(99, vec![page(1, "a", "published", None)]);
395            let tera = fresh_tera();
396            assert_eq!(render(&tera, r#"{{ children_filtered() | length }}"#), "1");
397        }
398        let tera = fresh_tera();
399        assert_eq!(render(&tera, r#"{{ children_filtered() | length }}"#), "0");
400    }
401
402    #[test]
403    fn serializes_full_page_shape() {
404        // Templates iterate the returned objects, so the shape MUST
405        // match the canonical Page JSON the public render context
406        // exposes for `children`. This pins both surfaces in sync.
407        let _g = install(99, vec![page(7, "post", "published", Some(123))]);
408        let tera = fresh_tera();
409        let out = render(
410            &tera,
411            r#"{% set p = children_filtered() %}{{ p[0].id }}-{{ p[0].slug }}-{{ p[0].status }}"#,
412        );
413        assert_eq!(out, "7-post-published");
414        // Pin against the same shape used by other ctx vars.
415        let json = serde_json::to_value(&page(7, "post", "published", Some(123))).unwrap();
416        assert_eq!(json["id"], json!(7));
417        assert_eq!(json["status"], json!("published"));
418    }
419}