duandan5471 2017-10-09 21:17
浏览 104
已采纳

Golang动态打印html行

I would like to print out rows from a mysql db as html. This is what I want to achieve:

<html>
<head>
...
</head>
<body>
<a href = "url1">name1</a>
<a href = "url2">name2</a>
...
</body>
</html>

My go code:

for rows.Next() {
    var name string
    var url string

    err = rows.Scan(&name, &url)
    if err != nil {
        log.Fatal(err)
    }
}

I thought that I could put the items into a slice and write them out with a for loop in a template, but instead of this is it possible to write out each line with the for loop in the go code?

  • 写回答

1条回答 默认 最新

  • doushen1026 2017-10-09 21:32
    关注

    It is possible but not a good idea. The template package is useful for escaping things which might have touched user input, and not hard to use. Just make a slice of things, and range over them in the template.

    This is safer than trying to build html in code because the context package knows about escaping urls or js for example, as opposed to html, and takes the location of variables into account.

    https://play.golang.org/p/JEIjPT5ayP

    package main
    
    import (
        "log"
        "os"
        "text/template"
    )
    
    var t = `
    <html>
    <head>
    ...
    </head>
    <body>
    {{range . }}
      <a href = "{{.URL}}">{{.Name}}</a>
    {{end}}
    </body>
    </html> 
    `
    
    type Location struct {
        Name string
        URL  string
    }
    
    func main() {
    
        // Insert read data code here
        data := []Location{{Name: "example", URL: "https://example.com"}}
    
        tmpl, err := template.New("foo").Parse(t)
        if err != nil {
            log.Fatal(err)
        }
    
        err = tmpl.Execute(os.Stdout, data)
        if err != nil {
            log.Fatal(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效