Macro laby::render

source ·
macro_rules! render {
    ($expr:expr) => { ... };
    ($($expr:expr),* $(,)?) => { ... };
}
Expand description

Renders the given value and returns the result as a String.

This is a convenience macro that constructs a new Buffer, renders the given expression into it, and returns the buffer as a String.

The value must implement the Render trait.

If multiple values are given, they are wrapped using the frag! macro and rendered sequentially without delimiters.

Expansion

// render!($expr)
{
    let mut buf = Buffer::new();
    $expr.render(&mut buf);
    buf.into_string()
}

// render!($expr*)
{
    render!(frag!($expr*))
}

Examples

Render a simple node as a string.

let s = render!(
    div!("content")
);

assert_eq!(s, "<div>content</div>");

This example constructs a more complex tree of nodes and renders it as a string.

let s = render!(
    html!(
        head!(title!("laby")),
        body!(p!("paragraph"))
    )
);

assert_eq!(s, "<html><head><title>laby</title></head><body><p>paragraph</p></body></html>");

The render! macro can render any value that implements the Render trait, which is not limited only to nodes constructed by markup macros. See the list of foreign impls on the Render trait to see which types are supported.

let v: u32 = 100;
assert_eq!(render!(v), "100");

All strings are escaped by default when rendered. This behavior can be opted out of by using the raw! macro.

let escaped = render!("a < b");
let raw = render!(raw!("a < b"));

assert_eq!(escaped, "a &lt; b");
assert_eq!(raw, "a < b");

This example renders multiple nodes using the render! macro. It is equivalent to passing a single argument using the frag! macro that wraps the values together.

let n = render!(div!(), span!());
let m = render!(frag!(div!(), span!()));

assert_eq!(n, "<div></div><span></span>");
assert_eq!(n, m);