lambda-fairy / maud

:pencil: Compile-time HTML templates for Rust
https://maud.lambda.xyz
Apache License 2.0
2.14k stars 143 forks source link

Make nested `html!` invocations lazy #381

Open mattfbacon opened 1 year ago

mattfbacon commented 1 year ago

Related to #373.

For patterns like this:

fn body() -> Markup { ... }

html! {
  h1 { "My page" }
  main { (body()) }
}

There is technically no need for the intermediate buffer from body, because the markup could render directly into the outer buffer.

In my ideal API, Markup would just implement Render (the render method would have to return something other than Markup, probably just PreEscaped<String>) and take advantage of the existing render_to method.

nikvoid commented 1 year ago

In my project (using #373) I solved it like this:

/// Helper for writing nested html_to!
/// Basically a lazy html! that can be rendered(-to) on demand
macro_rules! html_in {
    ($($tt:tt)*) => {
        MaudFnWrapper(|buf: &mut String| maud::html_to!{ buf, $($tt)* })
    };
}

/// A bit of closure magic to work around nested html_to!
struct MaudFnWrapper<F>(F);
impl<F> Render for MaudFnWrapper<F> 
where F: Fn(&mut String) {
    fn render_to(&self, buffer: &mut String) {
        self.0(buffer)
    }
}

Howerer this is mainly a workaround, than proper solution.

mattfbacon commented 1 year ago

Cool! I'll take a look at that and maybe make a PoC of my idea.

imbolc commented 3 weeks ago

Implemented in Hypertext. How difficult would it be to use the same approach in Maud?