Skip to main content

doido_view/
partials.rs

1//! Partial and collection rendering (Rails `render "posts/form"` /
2//! `render partial:, collection:`).
3//!
4//! A partial's file is the `_`-prefixed name in its directory, e.g.
5//! `render_partial("posts/form")` renders `posts/_form.html.tera`.
6
7use crate::render;
8use doido_core::Result;
9use serde_json::{json, Value};
10
11/// Render a single partial with `context`.
12pub fn render_partial(name: &str, context: &Value) -> Result<String> {
13    render(&partial_path(name), context)
14}
15
16/// Render `partial` once per item, exposing each item under `as_var`, and
17/// concatenate the results (Rails collection rendering).
18pub fn render_collection(partial: &str, items: &[Value], as_var: &str) -> Result<String> {
19    let mut out = String::new();
20    for item in items {
21        let ctx = json!({ as_var: item });
22        out.push_str(&render_partial(partial, &ctx)?);
23    }
24    Ok(out)
25}
26
27/// `posts/form` → `posts/_form`; `form` → `_form`.
28fn partial_path(name: &str) -> String {
29    match name.rsplit_once('/') {
30        Some((dir, base)) => format!("{dir}/_{base}"),
31        None => format!("_{name}"),
32    }
33}