duandong9195 2018-01-08 10:35
浏览 20
已采纳

将数据范围传递到HTML模板

I have inserted dummy data into the database.

The sample print function prints 13 and its square as per the code in the console. But I need to pass the entire data to the HTML template(index) where I can see a table of all the numbers passed with their respective square number.

How to pass this data in index HTML?

Number x Number = SquareNumber 1 x 1 = 1 2 x 2 = 4 3 x 3 = 9 ... and so on.

func main() {

    db, err := sql.Open("mysql", "root:@/godb")
    if err != nil {
        panic(err.Error())  
    }

    defer db.Close() 

 stmtIns, err := db.Prepare("INSERT INTO squarenum VALUES(?, ?, ? )") // ? = 
placeholder
    if err != nil {
        panic(err.Error()) }

    defer stmtIns.Close() 

 stmtOut, err := db.Prepare("SELECT squareNum FROM squareNum WHERE number = 
 ?")
    if err != nil {
        panic(err.Error()) 
    }

    defer stmtOut.Close()

    for i := 1; i < 50; i++ {
        _, err = stmtIns.Exec(0,i, (i * i)) 
        if err != nil {
            panic(err.Error()) 
        }
    }

    err = stmtOut.QueryRow(13).Scan(&squareNum) // WHERE number = 13
    if err != nil {
 panic(err.Error()) // proper error handling instead of panic in your app

    }
    tRes:=pageData{}
    tRes.SquareNum=squareNum
    fmt.Printf("The square number of 13 is: %d 
", squareNum)


    // Query another number.. 1 maybe?
    err = stmtOut.QueryRow(1).Scan(&squareNum) // WHERE number = 1
    if err != nil {
 panic(err.Error()) // proper error handling instead of panic in your app
    }
    fmt.Printf("The square number of 1 is: %d 
", squareNum)
    http.HandleFunc("/",idx)
    http.ListenAndServe(":8888", nil)
}

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

    pd := pageData{
        SquareNum: squareNum,
        }

    err := tpl.ExecuteTemplate(w, "index.html", pd)
    if err != nil {
        log.Println("LOGGED", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
        return
    }
}
  • 写回答

1条回答 默认 最新

  • dtg78700 2018-01-08 11:24
    关注
    package main
    
    import (
        "html/template"
        "os"
    )
    
    // here is your template
    const tplString = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>{{.Title}}</title>
    </head>
    <body>
    {{range .Dummies}}
    <div>Square of {{.Number}} is {{.Square}}</div>
    {{end}}
    </body>
    </html>
    `
    
    var (
        tpl *template.Template
        err error
    )
    
    // the dummydata you talked about
    type DummyData struct {
        Number int
        Square int
    }
    
    //some PageData just with dummies and a title
    type PageData struct {
        Title   string
        Dummies []*DummyData
    }
    
    //here you would be using your sql queries
    func createSomeDummies(amount int) []*DummyData {
        dummies := make([]*DummyData, amount)
        for i := 0; i < amount; i++ {
            dd := new(DummyData)
            dd.Number = i
            dd.Square = i * i
            dummies[i] = dd
        }
        return dummies
    }
    
    func main() {
        pd := new(PageData)
        pd.Title = "Hello Dummies"
        pd.Dummies = createSomeDummies(10)
    
        tpl = template.New("index")
        tpl, err = tpl.Parse(tplString)
        if err != nil {
            panic(err)
        }
        err = tpl.Execute(os.Stdout, pd)
        if err != nil {
            panic(err)
        }
    }
    

    This Snippet creates a PageData struct to hold the array of dummydata entries and a Title for the webpage.

    type PageData struct {
        Title   string
        Dummies []*DummyData
    }
    

    It then uses a function to create 10 dummydata structs. This array is then assigned to the Dummmies field of the PageData.

    pd.Dummies = createSomeDummies(10)
    

    This function is a placeholder for your sql query function you just have to loop over your sql rows instead of manually creating them like i do.

    func createSomeDummies(amount int) []*DummyData {
        dummies := make([]*DummyData, amount)
        for i := 0; i < amount; i++ {
            dd := new(DummyData)
            dd.Number = i
            dd.Square = i * i
            dummies[i] = dd
        }
        return dummies
    }
    

    The Template itself inserts the title like so: <title>{{.Title}}</title>

    The Dummies themselves are inserted by a range template directive that works like a for iterator. The one thing to be careful about is that inside this loop all data points to the DummyData item and not the PageData

    {{range .Dummies}}
    <div>Square of {{.Number}} is {{.Square}}</div>
    {{end}}
    

    Then the template is parsed. Errors will halt execution and print the error message.

    tpl = template.New("index")
    tpl, err = tpl.Parse(tplString)
    if err != nil {
        panic(err)
    }
    

    And finally the template will be rendered to Stdout. For use in a http Handler you would have to use the http.ResponseWriter instead. Once again errors halt execution and print the error message.

    err = tpl.Execute(os.Stdout, pd)
    if err != nil {
        panic(err)
    }
    

    Working Example here: Go Playground

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

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程