From c9257c265dc9f2df1189837ab76ad88fdca831a4 Mon Sep 17 00:00:00 2001 From: Mattias Jansson Date: Fri, 26 Sep 2025 13:28:07 +0200 Subject: [PATCH] Add Default trait impl for Lazy to enable struct field defaults Implement Default for Lazy), C> to support using `#[derive(Default)]` on structs containing Lazy fields (e.g., for component children). The default value creates an empty Lazy that renders nothing. --- hypertext/src/alloc/mod.rs | 7 ++++++ hypertext/tests/main.rs | 45 +++++++++++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/hypertext/src/alloc/mod.rs b/hypertext/src/alloc/mod.rs index 23e850d..ef85b52 100644 --- a/hypertext/src/alloc/mod.rs +++ b/hypertext/src/alloc/mod.rs @@ -312,6 +312,13 @@ impl), C: Context> Debug for Lazy { } } +impl Default for Lazy), C> { + #[inline] + fn default() -> Lazy), C> { + Lazy::dangerously_create(|_| ()) + } +} + /// A value rendered via its [`Display`] implementation. /// /// This will handle escaping special characters for you. diff --git a/hypertext/tests/main.rs b/hypertext/tests/main.rs index 974c0bb..9d93de0 100644 --- a/hypertext/tests/main.rs +++ b/hypertext/tests/main.rs @@ -3,7 +3,7 @@ use std::fmt::{self, Display, Formatter}; -use hypertext::{Buffer, Raw, maud_borrow, maud_static, prelude::*, rsx_borrow, rsx_static}; +use hypertext::{Buffer, Lazy, Raw, maud_borrow, maud_static, prelude::*, rsx_borrow, rsx_static}; #[test] fn readme() { @@ -749,3 +749,46 @@ fn toggles() { ); assert_eq!(rsx_result.as_inner(), r#""#); } + +#[test] +fn derive_default() { + #[derive(Default)] + struct Element<'a> { + pub id: &'a str, + pub tabindex: u32, + pub children: Lazy, + } + + impl<'a> Renderable for Element<'a> { + fn render_to(&self, buf: &mut Buffer) { + rsx! { +
+ (self.children) +
+ } + .render_to(buf) + } + } + + let with_children = rsx! { + +

hello

+
+ } + .render(); + + assert_eq!( + with_children.as_inner(), + r#"

hello

"# + ); + + let without_children = rsx! { + + } + .render(); + + assert_eq!( + without_children.as_inner(), + r#"
"# + ); +}