dphphvs496524 2012-09-10 17:23
浏览 9
已采纳

如何从MySQL传递值去模板

This struct to pass value to template

type Entry struct {
    Name, Mes string
}

This function to handle with HandleFunc("/", mysqlWithTempl)

func mysqlWithTempl(w http.ResponseWriter, r *http.Request) {

    // Open database
    con, err := sql.Open("mymysql", dbName+"/"+dbUserName+"/"+dbPassword)
    if err != nil {
        panic(err)
    }

    // Close database 
    defer con.Close()

    //query
    rows, err := con.Query("select name, message from entry")

    tRes := Entry{}

    //fetch result
    for rows.Next() {
        var name, message string
        rows.Scan(&name, &message)
        tRes.Name = name
        tRes.Mes = message
    }
    index.Execute(w, tRes)
}

and this template

<!DOCTYPE html>
<html>
    <head>
        <title> Test </title>
    </head>
    <body>
        <section id="contents">
        <p> {{.Mes}} {{.Name}} </p>
       </section>
    </body>
</html>

my ask how can fetch more value from mysql and pass it to template

When try

 for rows.Next() {
            var name, message string
            rows.Scan(&name, &message)
            tRes.Name = name
            tRes.Mes = message
index.Execute(w, tRes)
        }

all result fetched but every thing repeated

  • 写回答

1条回答 默认 最新

  • dpv21589 2012-09-10 20:45
    关注

    I think you might be asking how to show multiple results?

    If so then you want to accumulate all your rows into a slice like so:

    results := []Entry
    for rows.Next() {
        var name, message string
        rows.Scan(&name, &message)
        tRes.Name = name
        tRes.Mes = message
        results = append(results, tRes)
    }
    index.Execute(w, results)
    

    Then your template will change to look like this:

    <!DOCTYPE html>
    <html>
        <head>
            <title> Test </title>
        </head>
        <body>
            <section id="contents">
            {{range .}}
            <p> {{.Mes}} {{.Name}} </p>
            {{end}}
           </section>
        </body>
    </html>
    

    I believe this will cause one <p> {{.Mess}} {{.Name}} </p> to be run per row that your mysql query returns.

    I haven't actually tested this code though so it might have errors.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?