Initial commit
This commit is contained in:
69
app/internal/utils/render.go
Normal file
69
app/internal/utils/render.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Helper functions for templates
|
||||
var templateFuncs = template.FuncMap{
|
||||
"add": func(a, b int) int {
|
||||
return a + b
|
||||
},
|
||||
"sub": func(a, b int) int {
|
||||
return a - b
|
||||
},
|
||||
"eq": func(a, b interface{}) bool {
|
||||
return a == b
|
||||
},
|
||||
"pageRange": func(currentPage, totalPages int) []int {
|
||||
// Generate page numbers to show (max 7 pages)
|
||||
start := currentPage - 3
|
||||
end := currentPage + 3
|
||||
|
||||
if start < 1 {
|
||||
end += 1 - start
|
||||
start = 1
|
||||
}
|
||||
if end > totalPages {
|
||||
start -= end - totalPages
|
||||
end = totalPages
|
||||
}
|
||||
if start < 1 {
|
||||
start = 1
|
||||
}
|
||||
|
||||
var pages []int
|
||||
for i := start; i <= end; i++ {
|
||||
pages = append(pages, i)
|
||||
}
|
||||
return pages
|
||||
},
|
||||
}
|
||||
|
||||
func Render(w http.ResponseWriter, tmpl string, data interface{}) {
|
||||
// Paths for layout + page templates
|
||||
layout := filepath.Join("/Users/mannpatel/Desktop/Poll-system/app/internal/templates/", "layout.html")
|
||||
page := filepath.Join("/Users/mannpatel/Desktop/Poll-system/app/internal/templates/", tmpl)
|
||||
|
||||
// Parse files with helper functions
|
||||
tmpls, err := template.New("").Funcs(templateFuncs).ParseFiles(layout, page)
|
||||
if err != nil {
|
||||
http.Error(w, "Template parsing error: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Render to buffer first (catch errors before writing response)
|
||||
var buf bytes.Buffer
|
||||
err = tmpls.ExecuteTemplate(&buf, "layout", data)
|
||||
if err != nil {
|
||||
http.Error(w, "Template execution error: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Write final HTML to response
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
buf.WriteTo(w)
|
||||
}
|
||||
Reference in New Issue
Block a user