dioxus_html/
render_template.rs

1use dioxus_core::{Template, TemplateAttribute, TemplateNode};
2use std::fmt::Write;
3
4/// Render a template to an HTML string
5///
6/// Useful for sending over the wire. Can be used to with innerHtml to create templates with little work
7pub fn render_template_to_html(template: &Template) -> String {
8    let mut out = String::new();
9
10    for root in template.roots {
11        render_template_node(root, &mut out).unwrap();
12    }
13
14    out
15}
16
17fn render_template_node(node: &TemplateNode, out: &mut String) -> std::fmt::Result {
18    match node {
19        TemplateNode::Element {
20            tag,
21            attrs,
22            children,
23            ..
24        } => {
25            write!(out, "<{tag}")?;
26            for attr in *attrs {
27                if let TemplateAttribute::Static { name, value, .. } = attr {
28                    write!(out, "{name}=\"{value}\"")?;
29                }
30            }
31            for child in *children {
32                render_template_node(child, out)?;
33            }
34            write!(out, "</{tag}>")?;
35        }
36        TemplateNode::Text { text: t } => write!(out, "{t}")?,
37        TemplateNode::Dynamic { id: _ } => write!(out, "<!--placeholder-->")?,
38    };
39    Ok(())
40}