1

许多代码取自 Martini 示例,但这使用了 Echo 框架。

我可以让它在 Martini 中工作,但不能在 Echo 中工作。

server.go

package main

import (
    "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

(变量不是输出值)

4

1 回答 1

1

正如我在评论中提到的,您不应该执行一个模板,该模板采用带有结构切片的结构。要么{{range}}在你的模板中使用,要么做

c.Render(http.StatusOK, "onlytestingtpl", books[0])
于 2015-05-01T08:43:05.517 回答