dongxie548548 2017-12-04 23:32
浏览 105
已采纳

如何使用Golang模板显示HTML表

I am trying to use html/template package to display a table of information in a web page in Golang. The current implementation of the template I have outputs to standard out.

I want to be able to pass the page content generated by the template to another function that will render my web page.

How to achieve this?

Explanation of code attached below. Basically, I want to capture the result of t.Execute(os.Stdout, persons) where persons is a slice of string. I know that t.Execute only returns an error. But it prints to standard out the template t along with the person name values. I wanted to capture the combined template and person array texts into a variable instead. I would like to assign the content to the body variable in my code below.

    t := template.Must(template.New("").Parse(`<table>{{range .}}<tr><td>{{.}}</td></tr>{{end}}</table>`))

    if err := t.Execute(os.Stdout, persons); err != nil {
       log.Fatal(err)
    }
    title := "User Info Page"
    p := &Page{Title: title, Body: []byte(body)}
    renderTemplate(w, "view", p)
}
  • 写回答

1条回答 默认 最新

  • duanci6484 2017-12-04 23:39
    关注

    Execute the template to a bytes.Buffer. Use the contents of the buffer as the body.

    t := template.Must(template.New("").Parse(`<table>{{range .}}<tr><td>{{.}}</td></tr>{{end}}</table>`))
    
    var body bytes.Buffer
    if err := t.Execute(&body, persons); err != nil {
       log.Fatal(err)
    }
    title := "User Info Page"
    p := &Page{Title: title, Body: body.Bytes()}
    renderTemplate(w, "view", p)
    

    If it's also a requirement to print to stdout, then add the following code after executing the template:

    os.Stdout.Write(body.Bytes())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?