From b4c143b84ad600ff53ec8f9a0fa371a32e742ac1 Mon Sep 17 00:00:00 2001 From: Jonathan Cornaz Date: Sun, 3 Nov 2024 09:01:20 +0100 Subject: [PATCH] support `none` element --- README.md | 10 ++++++++-- src/elt.rs | 18 ++++++++++++++++++ src/lib.rs | 15 ++++++++++++--- tests/render_spec.rs | 2 ++ 4 files changed, 40 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 6d22dd2..2c889a9 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,14 @@ assert_eq!(greeting.to_string(), r#"

Hello world!

"#); Because those are simple rust functions, it is easy to leverage rust features like conditions, loops and iterators: ```rust -let list = ul([], (1..=3).map(|n| li([], [n.to_string().into()]))); -assert_eq!(list.to_string(), ""); +let list_values = true; +let element = if list_values { + ul([], (1..=3).map(|n| li([], [n.to_string().into()]))) +} else { + text("no value") +}; + +assert_eq!(element.to_string(), "") ``` diff --git a/src/elt.rs b/src/elt.rs index a36cdb5..8f1bb0e 100644 --- a/src/elt.rs +++ b/src/elt.rs @@ -8,6 +8,24 @@ use alloc::{borrow::Cow, string::String, vec::Vec}; use crate::{Attribute, Element, ElementInner}; +/// Renders nothing. Useful fo conditional rendering. +/// +/// # Example +/// +/// ``` +/// use fun_html::{Element, elt::{text, none}}; +/// +/// let say_hello = true; +/// let element: Element = if say_hello { +/// text("Hello") +/// } else { +/// none() +/// }; +/// ``` +pub fn none() -> Element { + Element(ElementInner::None) +} + /// `
` pub fn div( attributes: impl IntoIterator, diff --git a/src/lib.rs b/src/lib.rs index 00238d5..7471282 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,9 +27,16 @@ //! Because those are simple rust functions, it is easy to leverage rust features like conditions, loops and iterators: //! //! ``` -//! # use fun_html::{elt::{li,ul}}; -//! let list = ul([], (1..=3).map(|n| li([], [n.to_string().into()]))); -//! assert_eq!(list.to_string(), "
  • 1
  • 2
  • 3
"); +//! # use fun_html::{elt::{li,ul,text}}; +//! +//! let list_values = true; +//! let element = if list_values { +//! ul([], (1..=3).map(|n| li([], [n.to_string().into()]))) +//! } else { +//! text("no value") +//! }; +//! +//! assert_eq!(element.to_string(), "
  • 1
  • 2
  • 3
") //! ``` //! //! ## Escape hatches @@ -103,6 +110,7 @@ enum ElementInner { Script(Cow<'static, str>), Raw(Cow<'static, str>), Multiple(Vec), + None, } /// An attribute @@ -214,6 +222,7 @@ impl Display for Element { write!(f, "{elt}")?; } } + ElementInner::None => (), } Ok(()) } diff --git a/tests/render_spec.rs b/tests/render_spec.rs index 22f3e1e..172f01a 100644 --- a/tests/render_spec.rs +++ b/tests/render_spec.rs @@ -63,6 +63,8 @@ fn should_render_attribute(#[case] attr: Attribute, #[case] expected: &str) { } #[rstest] +#[case(none(), "")] +#[case([div([], []), div([], [])].into(), "
")] #[case(text("hello"), "hello")] #[case(text("hello".to_string()), "hello")] #[case("hello".into(), "hello")]