I have a file controllers/catalog.go it contains a HTTP handler:
func Catalog(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}
categories, err := models.GetCategories()
if err != nil {
http.Error(w, http.StatusText(500), http.StatusInternalServerError)
return
}
fmt.Print(categories)
config.TPL.ExecuteTemplate(w, "catalog.html", categories)
}
and models/getcategories.go:
type Cat_tree struct {
Cat_id int
Parent_id int
Cat_name string
}
func GetCategories() ([]Cat_tree, error) {
rows, err := config.DB.Query("SELECT cat_id, parent_id, cat_name FROM categories WHERE active = true ORDER BY Parent_id ASC")
if err != nil {
return nil, err
}
defer rows.Close()
categories := make([]Cat_tree, 0)
for rows.Next() {
cat := Cat_tree{}
err := rows.Scan(&cat.Cat_id, &cat.Parent_id, &cat.Cat_name)
if err != nil {
return nil, err
}
categories = append(categories, cat)
}
if err = rows.Err(); err != nil {
return nil, err
}
return categories, nil
}
How i can add some data to a categories page Title for example
Now in template like this
{{range .}}
<p><a href="/show?getinfo={{ .Cat_id}}">{{ .Cat_id}}</a> - {{ .Parent_id}} - {{ .Cat_name}} <a href="/show?getinfo={{ .Cat_id}}">Показать</a>
{{end}}
i'd like to add some {{Title}}
You have to create another struct and put categories and page info in there. you can use maps too, but struct is cleaner approach.
type Page struct {
Title string
Categories []Cat_Tree
}
func Catalog(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
return
}
categories, err := models.GetCategories()
if err != nil {
http.Error(w, http.StatusText(500), http.StatusInternalServerError)
return
}
page := Page {Title:"My Title",Categories:categories}
config.TPL.ExecuteTemplate(w, "catalog.html", page)
}
And in your template:
<h1>{{ .Title }}</h1>
{{range .Categories}}
<p><a href="/show?getinfo={{ .Cat_id}}">{{ .Cat_id}}</a> - {{ .Parent_id}} - {{ .Cat_name}} <a href="/show?getinfo={{ .Cat_id}}">Показать</a>
{{end}}
What I normally pass in to my template is a map[string]interface{}
:
data := make(map[string]interface{})
data["Categories"] = categories
data["Title"] = "This is the title"
config.TPL.ExecuteTemplate(w, "catalog.html", data)
<title>{{.Title}}</title>
<body>
{{range .Categories}}
<p><a href="/show?getinfo={{ .Cat_id}}">{{ .Cat_id}}</a> - {{ .Parent_id}} - {{ .Cat_name}} <a href="/show?getinfo={{ .Cat_id}}">Показать</a>
{{end}}
</body>