2020-05-20 14:28:08 +02:00
|
|
|
package templates
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"html/template"
|
2020-06-10 10:47:50 +02:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2020-05-20 14:28:08 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2020-06-10 10:47:50 +02:00
|
|
|
templatesPath = "/templates"
|
2020-05-20 14:28:08 +02:00
|
|
|
templateFileName = "template.html"
|
|
|
|
)
|
|
|
|
|
2020-06-10 10:47:50 +02:00
|
|
|
func GetParsedTemplate(dir http.FileSystem, contentData interface{}) (string, error) {
|
|
|
|
template, err := ParseTemplateFile(dir, "", contentData)
|
2020-05-20 14:28:08 +02:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return ParseTemplateText(template, contentData)
|
|
|
|
}
|
|
|
|
|
2020-06-10 10:47:50 +02:00
|
|
|
func ParseTemplateFile(dir http.FileSystem, fileName string, data interface{}) (string, error) {
|
2020-05-20 14:28:08 +02:00
|
|
|
if fileName == "" {
|
|
|
|
fileName = templateFileName
|
|
|
|
}
|
2020-06-10 10:47:50 +02:00
|
|
|
template, err := readFile(dir, fileName)
|
2020-05-20 14:28:08 +02:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return parseTemplate(template, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
func ParseTemplateText(text string, data interface{}) (string, error) {
|
|
|
|
template, err := template.New("template").Parse(text)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return parseTemplate(template, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseTemplate(template *template.Template, data interface{}) (string, error) {
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
if err := template.Execute(buf, data); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return buf.String(), nil
|
|
|
|
}
|
2020-06-10 10:47:50 +02:00
|
|
|
|
|
|
|
func readFile(dir http.FileSystem, fileName string) (*template.Template, error) {
|
|
|
|
f, err := dir.Open(templatesPath + "/" + fileName)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
content, err := ioutil.ReadAll(f)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
tmpl, err := template.New(fileName).Parse(string(content))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return tmpl, nil
|
|
|
|
}
|