许多代码取自 Martini 示例,但这使用 Echo 框架。我可以让它在 Martini 中运行,但不能在 Echo 中运行。server.go:package mainimport ( "database/sql" "github.com/labstack/echo" _ "github.com/lib/pq" "html/template" "io" "log" "net/http")type Book struct { Title, Author, Description string}type ( Template struct { templates *template.Template })func (t *Template) Render(w io.Writer, name string, data interface{}) error { return t.templates.ExecuteTemplate(w, name, data)}func main() { e := echo.New() db, err := sql.Open("postgres", "user=postgres password=apassword dbname=lesson4 sslmode=disable") if err != nil { log.Fatal(err) } t := &Template{ templates: template.Must(template.ParseFiles("public/views/testhere.html")), } e.Renderer(t) e.Get("/post/:idnumber", func(c *echo.Context) { rows, err := db.Query("SELECT title, author, description FROM books WHERE id=$1", c.Param("idnumber")) if err != nil { log.Fatal(err) } books := []Book{} for rows.Next() { b := Book{} err := rows.Scan(&b.Title, &b.Author, &b.Description) if err != nil { log.Fatal(err) } books = append(books, b) } c.Render(http.StatusOK, "onlytestingtpl", books) }) e.Run(":4444")}public/views/testhere.html:{{define "onlytestingtpl"}}Book title is {{.Title}}. Written by {{.Author}}. The book is about {{.Description}}.{{end}}我无法弄清楚,因为没有错误消息,也没有这个框架的 SQL 文档。运行时,它给出:Book title is(变量不是输出值)
1 回答
当年话下
TA贡献1890条经验 获得超9个赞
正如我在评论中提到的,您不应该执行一个模板,该模板采用一个结构体和一个结构体切片。要么{{range}}
在你的模板中使用,要么做
c.Render(http.StatusOK, "onlytestingtpl", books[0])
- 1 回答
- 0 关注
- 191 浏览
添加回答
举报
0/150
提交
取消