填充并列出嵌套结构

时间:2018-09-09 21:42:24

标签: go go-templates

有人可以帮我从嵌套的struct数据中填充模板吗,这里编码从mysql广告中获取数据的代码 em 很好

package main

import (
        "html/template"
        "log"
        "net/http"
        "database/sql"
        "github.com/gorilla/mux"
        _ "github.com/go-sql-driver/mysql"
)

var (
        o one
)

type one struct {
        point bool
        em    []two
}

type two struct {
        id  uint16
        uid uint16
}

func checkErr(err error) {
        if err != nil {
                log.Fatal(err)
        }
}

func listandlist(w http.ResponseWriter, r *http.Request) {
        db, err = sql.Open("mysql", "torwald:ragnar@tcp(127.0.0.1:3306)/harpy")
        checkErr(err)

        defer db.Close()

        err = db.Ping()
        checkErr(err)

        rows, err := db.Query("select * from global where point=?", o.point)
        checkErr(err)

        em := []two{}

        for rows.Next() {
                p := two{}
                err := rows.Scan(&p.id, &p.uid)
                if err != nil {
                        log.Println(err)
                        continue
                }
                log.Println("full list id and uid", p.id, p.uid)
                em = append(em, p)
        }

        if r.Method != "POST" {
                t, err := template.ParseFiles("templates/one.html", "templates/two.html", "templates/tree.html")
                if err != nil {
                        log.Fatal(w, err.Error())
                        return
                }
                t.ExecuteTemplate(w, "list", o)
                return

        }
}

但模板中为空

{{ define "list" }} {{ template "header" .}}
{{range .two}}
{{.id}}
{{.uid}}
{{end}}
{{ template "footer" }} {{ end }}

我坏了能告诉我吗?我如何从模板中的嵌套结构获取信息?

在mysql表全局中,我们有结构

TABLE `global` (
  `id` int(11) unsigned NOT NULL,
  `uid` int(11) unsigned NOT NULL,
  `point`  tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin

并填充数据,样本

id | uid | point
 1 |  2  |   0
 2 |  3  |   0
 2 |  1  |   1
 3 |  1  |   0
 1 |  3  |   0
 3 |  2  |   1

作为结果,我以point = 1运行此查询,我想在模板结果中看到两行:

2 1
3 2

0 个答案:

没有答案