html.go
This file
Path
render/html.go
92 lines · 2.5 KiB · Go
Last changed by
chore: update go.mod and remove space from copyright (#3158)thinkeroubefore adoption4b68a5f
History of this fileTake it
1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package render67import (8 "html/template"9 "net/http"10)1112// Delims represents a set of Left and Right delimiters for HTML template rendering.13type Delims struct {14 // Left delimiter, defaults to {{.15 Left string16 // Right delimiter, defaults to }}.17 Right string18}1920// HTMLRender interface is to be implemented by HTMLProduction and HTMLDebug.21type HTMLRender interface {22 // Instance returns an HTML instance.23 Instance(string, any) Render24}2526// HTMLProduction contains template reference and its delims.27type HTMLProduction struct {28 Template *template.Template29 Delims Delims30}3132// HTMLDebug contains template delims and pattern and function with file list.33type HTMLDebug struct {34 Files []string35 Glob string36 Delims Delims37 FuncMap template.FuncMap38}3940// HTML contains template reference and its name with given interface object.41type HTML struct {42 Template *template.Template43 Name string44 Data any45}4647var htmlContentType = []string{"text/html; charset=utf-8"}4849// Instance (HTMLProduction) returns an HTML instance which it realizes Render interface.50func (r HTMLProduction) Instance(name string, data any) Render {51 return HTML{52 Template: r.Template,53 Name: name,54 Data: data,55 }56}5758// Instance (HTMLDebug) returns an HTML instance which it realizes Render interface.59func (r HTMLDebug) Instance(name string, data any) Render {60 return HTML{61 Template: r.loadTemplate(),62 Name: name,63 Data: data,64 }65}66func (r HTMLDebug) loadTemplate() *template.Template {67 if r.FuncMap == nil {68 r.FuncMap = template.FuncMap{}69 }70 if len(r.Files) > 0 {71 return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...))72 }73 if r.Glob != "" {74 return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob))75 }76 panic("the HTML debug render was created without files or glob pattern")77}7879// Render (HTML) executes template and writes its result with custom ContentType for response.80func (r HTML) Render(w http.ResponseWriter) error {81 r.WriteContentType(w)8283 if r.Name == "" {84 return r.Template.Execute(w, r.Data)85 }86 return r.Template.ExecuteTemplate(w, r.Name, r.Data)87}8889// WriteContentType (HTML) writes HTML ContentType.90func (r HTML) WriteContentType(w http.ResponseWriter) {91 writeContentType(w, htmlContentType)92}