Http 向结构添加一些日期,然后将其放入go模板中
我有一个文件控制器/catalog.go它包含一个HTTP处理程序:Http 向结构添加一些日期,然后将其放入go模板中,http,go,Http,Go,我有一个文件控制器/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.GetCateg
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)
}
和模型/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}}
{{range.}
-{{.Parent_id}}-{{.Cat_name}
{{end}
我想添加一些
{{Title}
我通常传递给模板的是一个map[string]接口{}
:
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>
data:=make(映射[字符串]接口{})
数据[“类别”]=类别
数据[“标题”]=“这是标题”
config.TPL.ExecuteTemplate(w,“catalog.html”,数据)
{{.Title}
{{range.Categories}}
-{{.Parent_id}}-{{.Cat_name}
{{end}
您必须创建另一个结构,并将类别和页面信息放在其中。
您也可以使用映射,但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}}
{{.Title}
{{range.Categories}}
-{{.Parent_id}}-{{.Cat_name}
{{end}
Tnx!!你节省了我的时间!欢迎来到堆栈溢出!我对你的问题进行了编辑,使英语语法稍微标准化。