defined template and view directory seperately

This commit is contained in:
Chris kerr 2024-05-27 22:05:25 -04:00
parent 6f755be6cf
commit e699eec6e0
9 changed files with 37 additions and 17 deletions

View File

@ -3,16 +3,15 @@ package main
import (
"GoStart/src/api"
"GoStart/src/routes"
"GoStart/src/util"
"GoStart/src/utils"
"fmt"
"net/http"
)
func main() {
// Load Configurations
cfg, err := util.LoadConfig()
cfg, err := utils.LoadConfig()
if err != nil {
fmt.Printf("Failed to load config: %v\n", err)
return

View File

@ -10,5 +10,5 @@ func ExampleHandler(w http.ResponseWriter, r *http.Request) {
}
// Call renderTemplate with the specific template for this route
renderTemplate(w, data, "web/views/example.html")
renderTemplate(w, data, "example.html")
}

View File

@ -10,5 +10,5 @@ func RootHandler(w http.ResponseWriter, r *http.Request) {
}
// Call renderTemplate with the specific template for this route
renderTemplate(w, data, "web/views/index.html")
renderTemplate(w, data, "index.html")
}

View File

@ -1,6 +1,7 @@
package routes
import (
"GoStart/src/utils"
"html/template"
"net/http"
)
@ -9,16 +10,26 @@ type PageData struct {
Title string
}
func renderTemplate(w http.ResponseWriter, data PageData, view string) {
// List of common templates
layout := []string{
"web/views/template/#layout.html",
"web/views/template/#header.html",
"web/views/template/#footer.html",
// Define the base directories for views and templates
const (
viewsDir = "web/views/"
templatesDir = "web/views/templates/"
)
// Define the common layout templates filenames
var layoutFiles = []string{
"#layout.html",
"header.html",
"footer.html",
}
// Initialize the common templates with full paths
var layout = utils.PrependDir(templatesDir, layoutFiles)
func renderTemplate(w http.ResponseWriter, data PageData, view string) {
// Append the specific template for the route
templates := append(layout, view)
templates := append(layout, viewsDir+view)
// Parse all templates
tmpl, err := template.ParseFiles(templates...)

View File

@ -1,4 +1,4 @@
package util
package utils
import (
"encoding/json"

10
src/utils/helpers.go Normal file
View File

@ -0,0 +1,10 @@
package utils
// Helper function to prepend a directory path to a list of filenames
func PrependDir(dir string, files []string) []string {
var fullPaths []string
for _, file := range files {
fullPaths = append(fullPaths, dir+file)
}
return fullPaths
}