diff --git a/initializers/initializers.go b/initializers/initializers.go index 91588a1..f4c116b 100644 --- a/initializers/initializers.go +++ b/initializers/initializers.go @@ -7,7 +7,8 @@ import ( func initializePages() { Pages = make(map[string]Page) - Pages["index"] = Page{Path: "/", Template: "templates/index.html", Data: map[string]interface{}{"categories": Categories}} + Pages["index"] = Page{"/", "templates/index.html", map[string]interface{}{"categories": Categories}, nil} + Pages["category"] = Page{"/category", "templates/category.html", map[string]interface{}{}, DynamicDataLoaderCategory} } func initializeData() { diff --git a/market.go b/main.go similarity index 100% rename from market.go rename to main.go diff --git a/models/models.go b/models/models.go index 399205e..c4b3231 100644 --- a/models/models.go +++ b/models/models.go @@ -3,26 +3,41 @@ package models import ( "net/http" "html/template" + "strconv" ) type Page struct { Path string Template string Data map[string]interface{} + DynamicDataLoader func(int) map[string]interface{} +} + +func DynamicDataLoaderCategory(id int) map[string]interface{}{ + return map[string]interface{}{ + "category": GetCategoryById(id), + "products": GetCategoryProducts(id), + } } func (p Page) HandlePage(w http.ResponseWriter, r *http.Request) { + if p.DynamicDataLoader != nil { + id, err := strconv.Atoi(r.URL.Query()["id"][0]) + if err == nil { + p.Data = p.DynamicDataLoader(id) + } + } t, _ := template.ParseFiles(p.Template, "templates/base.html") t.ExecuteTemplate(w, "base", p.Data) } type Category struct { - Id uint + Id int Name string } type Product struct { - Id uint + Id int Category Category Name string Description string @@ -45,3 +60,25 @@ func GetCategoryByName(name string) Category { } return category } + +func GetCategoryById(id int) Category { + var category Category + for i:= range Categories { + if Categories[i].Id == id { + category = Categories[i] + break + } + } + return category +} + +func GetCategoryProducts(id int) []Product { + var products []Product + for i:= range Products { + if Products[i].Category.Id == id { + products = append(products, Products[i]) + break + } + } + return products +} diff --git a/templates/base.html b/templates/base.html index f86a8a8..cd32476 100644 --- a/templates/base.html +++ b/templates/base.html @@ -9,7 +9,7 @@ - [logo] + [Strona główna] {{template "content" .}} diff --git a/templates/category.html b/templates/category.html new file mode 100644 index 0000000..618020c --- /dev/null +++ b/templates/category.html @@ -0,0 +1,6 @@ +{{define "content"}} + {{.category.Name}} + {{range $.products}} + {{ .Name }} + {{end}} +{{end}} diff --git a/templates/index.html b/templates/index.html index f3d06d5..eaa6911 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,5 +1,5 @@ {{define "content"}} {{range $.categories}} - {{ .Name }} + {{ .Name }} {{end}} {{end}}