我有一个文件controllers / catalog.go,它包含一个HTTP处理程序:
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)
}
和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
}
例如我如何向类别页面标题中添加一些数据
现在在这样的模板中
{{range .}}
<p><a href="/show?getinfo={{ .Cat_id}}">{{ .Cat_id}}</a> - {{ .Parent_id}} - {{ .Cat_name}} <a href="/show?getinfo={{ .Cat_id}}">Показать</a>
{{end}}
我想添加一些{{Title}}
答案 0 :(得分:1)
我通常传递给模板的是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>
答案 1 :(得分:0)
您必须创建另一个结构,然后在其中放置类别和页面信息。 您也可以使用地图,但是struct是更简洁的方法。
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)
}
在您的模板中:
<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}}