Files
raccws/racc_template/racc_template.go
2025-07-12 23:09:54 +02:00

82 lines
2.2 KiB
Go

package racc_template
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
)
var templates = template.Must(template.ParseFiles("./html-templates/index.html"))
func WriteTemplate(title, description, templatedir string, status int) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
initTemplates(templatedir)
w.WriteHeader(status)
//fmt.Println("Status WriteTemplate ", status)
renderTemplate(w, "html-templates/application_mainframe.html", nil)
})
}
}
func RenderApplicationTemplate(tmpl string, data interface{}) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
a, b := template.ParseFiles("html-templates/application_mainframe.html", tmpl)
fmt.Println(b)
tmpls := template.Must(a, b)
c := tmpls.ExecuteTemplate(w, "application_mainframe.html", data)
fmt.Println(c)
})
}
}
func RenderApplicationTemplateHandler(tmpl string, data interface{}) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
a, b := template.ParseFiles("html-templates/application_mainframe.html", tmpl)
fmt.Println(b)
tmpls := template.Must(a, b)
c := tmpls.ExecuteTemplate(w, "application_mainframe.html", data)
fmt.Println(c)
})
}
func ProcessTemplate(w http.ResponseWriter, templatename, templatedir string, status int, data interface{}) {
initTemplates(templatedir)
w.WriteHeader(status)
//fmt.Println("Status ProcessTemplate ", status)
renderTemplate(w, templatename, data)
}
func initTemplates(directory string) {
files, err := os.ReadDir(directory)
if err != nil {
log.Fatal(err)
}
var filePaths []string
for _, file := range files {
if !file.IsDir() {
filePaths = append(filePaths, filepath.Join(directory, file.Name()))
}
}
fmt.Println(filePaths)
tmpl, err := template.ParseFiles(filePaths...)
if err != nil {
log.Fatal(err)
}
templates = template.Must(tmpl, err)
}
func renderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
err := templates.ExecuteTemplate(w, tmpl, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}