maud icon indicating copy to clipboard operation
maud copied to clipboard

Allow writing to existing html buffer

Open nikvoid opened this issue 2 years ago • 1 comments

Another attempt to add feature requested in #90. This PR add html_to! macro that can use existing String as output buffer. Example:

use maud::{self, html, html_to, Render};

#[test]
fn html_render_to_buffer() {
    let mut buf = String::new();

    html_to! { buf 
        p { "existing" }
    };
    
    assert_eq!(buf, "<p>existing</p>");
}

#[test]
fn html_buffer_reuse() {
    let mut buf = String::new();
    html_to! { buf 
        p { "existing" }
    };
    
    html_to! { buf 
        p { "reused" }
    };
    
    assert_eq!(buf, "<p>existing</p><p>reused</p>");
}

#[test]
fn impl_render_to_html_to() {
    struct Foo;
    impl Render for Foo {
        fn render_to(&self, buffer: &mut String) {

            html_to! { buffer
                a { "foobar" }                
            }
        }
    }

    let rendered = html! {
        p { (Foo) }
    }.into_string();
    
    assert_eq!(rendered, "<p><a>foobar</a></p>");
}

I'm requesting comments on how to improve this and fit it better into existing code

nikvoid avatar Apr 12 '23 14:04 nikvoid

Oh, just realized that this won't work simply when trying to interpolate Render value in html_to! because of &mut reference. image

nikvoid avatar Apr 12 '23 15:04 nikvoid