1
0
mirror of https://github.com/schollz/cowyo.git synced 2023-08-10 21:13:00 +03:00
cowyo/vendor/github.com/gin-contrib/multitemplate/multitemplate.go

79 lines
1.9 KiB
Go
Raw Permalink Normal View History

2017-10-03 21:43:55 +03:00
package multitemplate
import (
"html/template"
"path/filepath"
"github.com/gin-gonic/gin/render"
)
// Render type
type Render map[string]*template.Template
var _ render.HTMLRender = Render{}
// New instance
func New() Render {
return make(Render)
}
// Add new template
func (r Render) Add(name string, tmpl *template.Template) {
if tmpl == nil {
panic("template can not be nil")
}
if len(name) == 0 {
panic("template name cannot be empty")
}
r[name] = tmpl
}
// AddFromFiles supply add template from files
func (r Render) AddFromFiles(name string, files ...string) *template.Template {
tmpl := template.Must(template.ParseFiles(files...))
r.Add(name, tmpl)
return tmpl
}
// AddFromGlob supply add template from global path
func (r Render) AddFromGlob(name, glob string) *template.Template {
tmpl := template.Must(template.ParseGlob(glob))
r.Add(name, tmpl)
return tmpl
}
// AddFromString supply add template from strings
func (r *Render) AddFromString(name, templateString string) *template.Template {
tmpl := template.Must(template.New(name).Parse(templateString))
r.Add(name, tmpl)
return tmpl
}
// AddFromStringsFuncs supply add template from strings
func (r *Render) AddFromStringsFuncs(name string, funcMap template.FuncMap, templateStrings ...string) *template.Template {
tmpl := template.New(name).Funcs(funcMap)
for _, ts := range templateStrings {
tmpl = template.Must(tmpl.Parse(ts))
}
r.Add(name, tmpl)
return tmpl
}
// AddFromFilesFuncs supply add template from file callback func
func (r Render) AddFromFilesFuncs(name string, funcMap template.FuncMap, files ...string) *template.Template {
tname := filepath.Base(files[0])
tmpl := template.Must(template.New(tname).Funcs(funcMap).ParseFiles(files...))
r.Add(name, tmpl)
return tmpl
}
// Instance supply render string
func (r Render) Instance(name string, data interface{}) render.Render {
return render.HTML{
Template: r[name],
Data: data,
}
}