github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/view/xml/render.go (about)

     1  package xml
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"strings"
     7  
     8  	"github.com/egonelbre/exp/view"
     9  )
    10  
    11  type renderer struct{ io.Writer }
    12  
    13  func (r renderer) Render(indent string, node *view.Node) error {
    14  	fmt.Fprintf(r, "%s<%s", indent, node.Type)
    15  	if node.Name != "" {
    16  		fmt.Fprintf(r, " class='%s'", node.Name)
    17  	}
    18  	for _, prop := range node.Props {
    19  		fmt.Fprintf(r, " %s='%s'", strings.ToLower(prop.Name), prop.Value)
    20  	}
    21  	fmt.Fprintf(r, ">")
    22  	if len(node.Children) > 0 {
    23  		fmt.Fprintln(r)
    24  	}
    25  	for _, child := range node.Children {
    26  		r.Render(indent+"\t", child)
    27  	}
    28  	if len(node.Children) > 0 {
    29  		fmt.Fprint(r, indent)
    30  	}
    31  	fmt.Fprintf(r, "<\\%s>\n", node.Type)
    32  	return nil
    33  }
    34  
    35  func Render(root *view.Node, w io.Writer) error {
    36  	return renderer{w}.Render("", root)
    37  }