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 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测