// Package view handles WebUI generation for clustvirt. The methods and utilties in this module control what is viewed, // templates that are loaded, and building those templates. Caching is not considered beyond what is done // automattically by go (if anything). package view import ( "html/template" "io" "log" "os" ) // View is responsible for assembling a group of templates, providing // methods to add data and compose pages in a common way. type View struct { content string template *template.Template } var basetemplate *template.Template // New returns a new instance of the View, expecting the content to be the actual // content as a template defining "content", in string format. func New(content string) *View { if basetemplate == nil { log.Println("Initializing base template") basetemplate = template.Must(template.New("").ParseFiles(index, header, footer)) } log.Println("Cloning base template") v := &View{template: template.Must(basetemplate.Clone())} v.parse(content) return v } // NewFromFile loads a template from a file func NewFromFile(file string) (*View, error) { b, err := os.ReadFile(file) return New(string(b)), err } func (v *View) parse(tmpl string) error { log.Println("Parsing template contents") if _, err := v.template.Parse(tmpl); err != nil { return err } log.Println("Template parsed") return nil } // Render returns the executed template with data func (v *View) Render(w io.Writer, data any) error { log.Println("Excuting template") return v.template.ExecuteTemplate(w, "_index", data) }